ndnguyen
ndnguyen

Reputation: 140

Avoid exit application when press back button

I don't know why every times I click default back button, it close my app immediately.

I don't use :

_ android:noHistory="true" in Manifest xml file
_ newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) before start new activity

My activity in Manifest xml file is:

<activity
    android:name="com.example.canvas_bar.member.MemberActivity"
    android:screenOrientation="portrait"
    android:label="@string/title_activity_member" >
</activity>

My backPress function:

 @Override
    public void onBackPressed() 
    {
       Log.e("back", "Last matches : pressed accepted");
       super.onBackPressed();
    }

My Code of replacing Activity ( in a tab of Tabhost)

  public void replaceContentView(String id, Intent newIntent) 
{
    try
    {
        View view =  getLocalActivityManager()
                    .startActivity(id,newIntent) 
                    .getDecorView();
        this.setContentView(view);
    }
    catch(Exception e)
    {
        String msg = e.getMessage();
        Log.d("Change Activity", msg);
    }
}

In Log Cat, it shows:

TRACE stop requested, but not running

Please help me. Thanks

Upvotes: 0

Views: 1811

Answers (3)

Naddy
Naddy

Reputation: 2674

I guess this is the default behavior of TabHost. You are simply replacing ContentView. If you start another Activity like this-

startActivity(new Intent(this,YourClass.class));

where YourClass is a separate class then this problem won't happen but since you have replaced it in the same Tab the problem happens. A simple tweak would be to go back to the previous Activity explicitly. You can in your onBackPressed provide an Intent to go back to the previous Activity.

Edit- You cannot obtain previous Tab but you can store the information yourself. Just keep a record of previous tab in your class that listens for onTabChanged().

static TabHost mytabs;

mytabs = getTabHost();

mytabs.setOnTabChangedListener(new OnTabChangeListener() {
    @Override
    public void onTabChanged(String arg0) {         

        Log.i("***Selected Tab", "Im currently in tab with index::" + mytabs.getCurrentTab());
    }       
});  

You get your current tab so store it. When the next change occurs just retrieve the stored value and replace it with current value.

Upvotes: 1

Shashika
Shashika

Reputation: 1161

Post the code you use to start this activity. May be you finish() the calling activity after this is started. So pressing back may be closing the app, instead of going back to the previous activity.

Upvotes: 0

pinxue
pinxue

Reputation: 1746

Can't see where the log comes. But the source code posted just uses default behavior, which is to stop the activity.

Try to comment out super.onBackPressed();

Upvotes: 0

Related Questions