首先 我们能想到的是 onBackPressed 是 Android 中的一个回调方法,当用户按下设备的返回按钮时触发。通常用于处理返回按钮的逻辑,例如关闭当前 Activity 或执行特定操作。
@Override
public void onBackPressed() {
// 自定义返回逻辑
super.onBackPressed(); // 调用父类方法关闭 Activity
}
在单应用场景中,我们是这样实现操作拦截的。那么如何在所有应用中实现拦截功能呢?首先想到的方案是:
在 frameworks/base/core/java/android/app/Activity.java 文件中,父类的 onBackPressed() 方法可以实现全局拦截。
不过需要注意的是,我们只需要在所有应用的最后一个页面进行拦截。通过查阅源码发现…
@Deprecated
public void onBackPressed() {
////检查并尝试折叠ActionBar的展开视图
if (mActionBar != null && mActionBar.collapseActionView()) {
return;
}
/////检查并尝试弹出FragmentManager中的返回栈
FragmentManager fragmentManager = mFragments.getFragmentManager();
if (!fragmentManager.isStateSaved() && fragmentManager.popBackStackImmediate()) {
return;
}
onBackInvoked();
}
在onBackInvoked()里面
private void onBackInvoked() {
// Inform activity task manager that the activity received a back press.
// This call allows ActivityTaskManager to intercept or move the task
// to the back when needed.
Log.e(TAG,"其他的应用页面");
if (!isTaskRoot()) {
Log.e(TAG,"主应用页面");
///把“是否结束 Activity”的决定权交给 ActivityTaskManagerService (ATMS)。
ActivityClient.getInstance().onBackPressed(mToken,
new RequestFinishCallback(new WeakReference<>(this)));
getAutofillClientController().onActivityBackPressed(mIntent);
}
}
/**
* Return whether this activity is the root of a task. The root is the
* first activity in a task.
*
* @return True if this is the root activity, else false.
*/
public boolean isTaskRoot() {
return mWindowControllerCallback.isTaskRoot();
}
isTaskRoot()方法
- 判断当前Activity是否是任务栈的根Activity
- 根Activity是指任务栈中的第一个Activity
- 通过mWindowControllerCallback.isTaskRoot()实现具体判断
通过这种判断方式,可以拦截那些未重写 onBackPressed() 方法的应用程序。






