androidandroid-intent

How to manually pause Activity in Android


I have two Activities , A and B. I called B from A throught this code :

 Intent myIntent = new Intent(this, myAcitivity.class);        
 myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(myIntent);

and on B , I placed a button to go back to activity A by pausing activity B. I tried to pause B so that it goes to background and go to A , but it is working. I tried

One Solution :

moveTaskToBack(true);

Instead of placing B in background , it is also placing A in background.

Any solutions ?


Solution

  • Android is already doing this for you. Say you are in activity A. You start activity B with:

    Intent myIntent = new Intent(this, myAcitivity.class);
    startActivity(myIntent);
    

    onPause() for current activity will be called before you go to myActivity, where onCreate() gets called. Now if you press back button, myActivity's onPause() gets called, and you move back to activity A, where onResume() is called. Please read about activity life cycle in the docs here and here.

    To save the state of an activity, you must override onSaveInstanceState() callback method:

    The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.

    Example:

    static final String STATE_SCORE = "playerScore";
    static final String STATE_LEVEL = "playerLevel";
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state
        savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
        savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
    
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }
    

    And when your activity is recreated, you can recover your state from the Bundle:

    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Always call the superclass so it can restore the view hierarchy
        super.onRestoreInstanceState(savedInstanceState);
    
        // Restore state members from saved instance
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    }
    

    There's more on this in the docs, please have a good read about saving/restoring your activity state here.