Search code examples
androidstart-activityonbackpressed

Going to the apps screen when pressing the back button in android


I have an android app my app needs to go to the Apps screen when i press Back button, So i'am using the following code for that purpose

@Override
public void onBackPressed()
 { 
    Intent i= new Intent(Intent.ACTION_ALL_APPS);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addCategory(Intent.CATEGORY_HOME);
    startActivity(i); 
}

But it doesn't work and say "unfortunately Your application has stopped"
who know what is the problem , or provide another way to do same thing


Solution

  • You can do this by using below Intent. This intent will start the Launcher app that the user has defined.

    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);    
    

    Or you can also use this one line solution:

    moveTaskToBack(true);  // activity.moveTaskToBack(true)
    

    it will behave as Home Button is pressed