Friday, February 22, 2019

Reopen app when press Back button

Normaly, when we press Back button, current screen will be exit. If want Back button not work, use this.
@Override
public void onBackPressed() {

}
There no line super.onBackPressed()inside;
This way make Back button doesn’t work, if user using application screen and want back to home screen, they must use Home button.
We want press Back button to go to home screen and reopen class.
Add these lines in to onBackPress() command.
Intent startMain = new Intent(Intent.ACTION_MAIN);
     startMain.addCategory(Intent.CATEGORY_HOME);
     startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startMain.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startMain.putExtra("ID_TimeLeft", String.valueOf(0));
     startActivity(startMain);
     finish();

Add these lines in to above last close bracket.
@Override
     public void onStop() {
          super.onStop();
     Intent i=new Intent(this,MainActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    i.putExtra("ID_TimeLeft",String.valueOf(0));
    startActivity(i);
   }

Now we can back to home screen and reopen class.

No comments:

Post a Comment