If you press back key,it will move you immediate back Screen/Activity. Not the Device Home Screen or your desired activity.
Solution: For this kind of situation, you can use onKeyLongPress, an override methods of an Activity. Lets do the tricks.
What I do here? close an app from any activity by long pressing the device back key.
Suppose you are now in Activity Z & wanna go to Device home Screen (exiting your application) when user press long time on Back Key. Just override the onKeyLongPress in activity Z, send a boolean value to Activity A.
public class Z extends Activity {
// From here you will go to Device Home Activity or wherever you want
.....
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// if you want to go your Main Activity A
Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// a string value is sent to Activity A
intent.putExtra("exit", true);
startActivity(intent);
return true;
}
return super.onKeyLongPress(keyCode, event);
}
}
In onResume() methods of Activity A, Check the boolean value & call finish() methods which is responsible to close an activity.
public class A extends Activity {
// this is your Main/Home Activity
...
@Override
protected void onResume() {
// here you check the string and finish the Main Activity
// exiting your application
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
// if you not exit your application,no need to check.
super.onResume();
}
}
Bonus Code: You can directly go to device home screen by pasting below code.
// if you want to go device home screen
Intent homeScreenIntent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeScreenIntent);