Android 應用退到背景
2016-4-21 10:29:26
Android L
moveTaskToBack(boolean nonRoot)
把包含這個Activity的任務轉到背景。并不是finish。
傳入Boolean參數:如果是false,在這個Activity是任務的根Activity時,方法才會起效。
傳入true,任務中任意Activity都會起效。
/**
* Move the task containing this activity to the back of the activity
* stack. The activity's order within the task is unchanged.
*
* @param nonRoot If false then this only works if the activity is the root
* of a task; if true it will work for any activity in
* a task.
*
* @return If the task was moved (or it was already at the
* back) true is returned, else false.
*/
public boolean moveTaskToBack(boolean nonRoot) {
try {
return ActivityManagerNative.getDefault().moveActivityTaskToBack(
mToken, nonRoot);
} catch (RemoteException e) {
// Empty
}
return false;
}
我們可以監聽菜單鍵,按菜單鍵把APP退到背景:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
moveTaskToBack(true);// 點選菜單鍵即轉入背景,vivo X6Plus Android5.1也适用
return true;
}
}
點選傳回鍵,退出目前Activity
點選傳回鍵,執行
onBackPressed()
,最後會調用
finish()
。但是程序并沒有被殺死。
Activity會進入onPause()。在合适的時機,Activity會進入onResume(),恢複狀态。
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
public void onBackPressed() {
if (!mFragments.getSupportFragmentManager().popBackStackImmediate()) {
supportFinishAfterTransition();
}
}
/**
* Reverses the Activity Scene entry Transition and triggers the calling Activity
* to reverse its exit Transition. When the exit Transition completes,
* {@link #finish()} is called. If no entry Transition was used, finish() is called
* immediately and the Activity exit Transition is run.
*
* <p>On Android 4.4 or lower, this method only finishes the Activity with no
* special exit transition.</p>
*/
public void supportFinishAfterTransition() {
ActivityCompat.finishAfterTransition(this);
}
/**
* Reverses the Activity Scene entry Transition and triggers the calling Activity
* to reverse its exit Transition. When the exit Transition completes,
* {@link Activity#finish()} is called. If no entry Transition was used, finish() is called
* immediately and the Activity exit Transition is run.
*
* <p>On Android 4.4 or lower, this method only finishes the Activity with no
* special exit transition.</p>
*/
public static void finishAfterTransition(Activity activity) {
if (Build.VERSION.SDK_INT >= 21) {
ActivityCompat21.finishAfterTransition(activity);
} else {
activity.finish();
}
}