在做应用层APP需求的过程中,HOME键的监听,Back键的监听,这都是很常见的问题,那你有试过,去拦截HOME键的事件吗,有去了解过如何处理吗,流程如何
首先大家应该先了解一种情况,就是Android在应用中是无法拦截Home键的,今天我们带大家看一下Home键的三种情况。
1、在应用中按下Home键的逻辑处理
xref: /frameworks/base/services/core/java/com/android/server/policy/PhoneWindowManager.java
这是源码的具体类跟地址
创建一个启动到桌面的Intent。
Intent mHomeIntent;
mHomeIntent = new Intent(Intent.ACTION_MAIN, null);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
startActivity(mHomeIntent);
2、在应用中监听Home键
在Android应用中如果想监听Home键可以使用广播机制,这个在源码中也有体现。
这样就可以监听Home的是否被按下。
static public final String SYSTEM_DIALOG_KEY = "reason";
static public final String SYSTEM_DIALOG_GLOBAL_ACTIONS = "globalactions";
static public final String SYSTEM_DIALOG_RECENT_APPS = "recentapps";
static public final String SYSTEM_DIALOG_HOME_KEY = "homekey";
static public final String SYSTEM_DIALOG_ASSIST = "assist";
@Override
public void onReceive(Context arg0, Intent arg1) {
String action = arg1.getAction();
//按下Home键会发送ACTION_CLOSE_SYSTEM_DIALOGS的广播
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = arg1.getStringExtra(SYSTEM_DIALOG_KEY);
if (reason != null) {
if (reason.equals(SYSTEM_DIALOG_HOME_KEY)) {
// 短按home键
Toast.makeText(arg0, "短按Home键", Toast.LENGTH_SHORT).show();
} else if (reason.equals(SYSTEM_DIALOG_RECENT_APPS)) {
// RECENT_APPS键
Toast.makeText(arg0, "RECENT_APPS", Toast.LENGTH_SHORT).show();
}
}
}
}
3、在Frameworks层拦截Home键
xref: /frameworks/base/services/core/java/com/android/server/policy/PhoneWindowManager.java
直接在onKeyDown中判断通过keyCode == KeyEvent.KEYCODE_HOME是不能拦截的
/** {@inheritDoc} */
@Override
public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
......
// First we always handle the home key here, so applications
// can never break it, although if keyguard is on, we do let
// it handle it, because that gives us the correct 5 second
// timeout.
if (keyCode == KeyEvent.KEYCODE_HOME) {
// If we have released the home key, and didn't do anything else
// while it was pressed, then it is time to go home!
if (!down) {
//添加的判断当前前台运行APP代码
if (!isBackgroundActivity(mContext, PKG_NAME_xxxxx)) {
Log.d(TAG, "xxxx app is foreground");
if (!getTopActivity(mContext).equals(ACTIVITY_NAME_xxxx)) {
Log.d(TAG, "xxxxx app is foreground activity");
return -1;
}
return -1;
}
cancelPreloadRecentApps();
mHomePressed = false;
if (mHomeConsumed) {
mHomeConsumed = false;
return -1;
}
......