Search code examples
androidandroid-activityonresume

Restart Android activity on relaunch of application


I had 3 activities in an android application. The application will exit when I press back button in each activity. Using the following code.

When I press back from the third activity, the application exits fine but when I relaunch the application by clicking the app icon, then the third activity will launch again. But I need to launch my main activity at the time of such "relaunch".

I tried write the code on "onResume" but not working.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
        moveTaskToBack(true);
        return true;
    }
        return super.onKeyDown(keyCode, event);
}

Please help me. Thanks in advance


Solution

    1. Create three activities - A, B and C
    2. In Activity A - when calling startActivity(B), call finish() also. Example -

       public void onButtonClick() // Some method 
       {
          startActivity(intentForB);
          finish();
      }
      
    3. Similarly when going to C from B -

       public void onButtonClick()
       {
          startActivity(intentForC);
          finish();
       }
      
    4. When the user is on Activity C and when he presses the back button , the application will get closed.(No need to write back button handling explicitly).

    Hope this helps.