onBackPressed to hide Not destroy activity
i know how to cancel back keypress, so that the activity / main window stays visible:
public void onBackPressed() {
return;
}
my aim is to hide the activity, however, without finishing it, how do you do that in the onBackPressed event?
i.e. 开发者_运维问答I would like to get as far as onPause(), but not evoke the onBackPressed() default behaviour that essentially calls finish(). another way to put it is that i would like to mimic onUserLeaveHint() ?
any help appreciated!
If you want to mimic the "Home" button on specific Activities just do this:
Below API 5:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Above and on API 5:
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
It will move the Task to background.. when you return, it will be as it was.
You can see more information about this here: Override back button to act like home button
If you want to mimic the "Home" button on specific Activities :
1st Method :
@Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
2nd Method :
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
And if you want to move to the previous activity without destroying current :
@Override
public void onBackPressed() {
startActivity(new Intent(CurrentActivity.this, DestinationActivity.class);
}
And now from any activity if you want to open the activity which is in Background . I name CurrentActivity. you could call it form anywhere..like..it wil take that actvity and put it to top of stack . and open it where you left off.
Intent intent = new Intent(FromAnyActivity.this, CurrentActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
Flags :
FLAG_ACTIVITY_REORDER_TO_FRONT
: To reorder the activity from stack
FLAG_ACTIVITY_CLEAR_TOP
: To remove all the activities from the top
If you don't destroy your activity you must set acitvity launch mode to single_instance and use moveTaskToBack(true) to send to background.
Well, you can't move back in the current stack without finish
ing the activity. Perhaps you could detect onBackPressed()
and then launch the home intent in a new task:
public void onBackPressed() {
Intent i = new Intent("android.intent.action.MAIN");
i.addCategory("android.intent.category.HOME");
i.addCategory("android.intent.category.DEFAULT");
i.addCategory("android.intent.category.LAUNCHER");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
return;
}
Let me know if that works.
精彩评论