您的位置:首页 > 移动开发 > Android开发

Android 应用退到后台

2016-04-21 22:36 369 查看

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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: