Android 应用退到后台

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();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值