Search code examples
androidandroid-activitytaskback-button

Recreate activity or just take it from task?


the question is a bit malformed. Sorry. I wanted to say that when you click software back button (actionBar 'up' button - created by android, when you established parentActivity in manifest) that button recreates an activity that is considered "father" (if i'm not wrong).

But i can override that with something like this:

    @Override
public boolean onOptionsItemSelected(MenuItem item)
{
    switch (item.getItemId()) {

        case android.R.id.home:
            onBackPressed();
            return true;
    }


    return super.onOptionsItemSelected(item);
}

In that way if i understand correctly activity is not recreated. Activity on top just finish()ed and we see activity that was under it saved in task. Right?

Considering that i am not passing any data back, what should i use or what is better: default or overrided behavior? What risks i run into if i will not recreate an activity and override the method changing the behavior? can an activity from task be lost? ( in case i am saying wth things right now, pls excuse me :D )


Solution

  • I will suggest to use this

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true; 
        } 
        return super.onOptionsItemSelected(item);
    }
    

    rather than this,

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
        return super.onOptionsItemSelected(item);
    }
    

    Reason:

    When you apply the second approach, FirstActivity will be launched again that means onCreate() will be called, whether in first approch onRestart() will be called as I suggested in comment.

    Note: If you want to reload FirstActivty on android.R.id.homepress event, use second approch.