需求描述
厂测app需要测试电源键,发现拦截不到,早期Android版本的方法也不行。网上文章有些收费无法查看,应该提倡开源共享的。
参考资料
Android14 WMS-Power键短按流程_powerkeyrule-CSDN博客
具体方法
进入厂测app按键测试下时设置persist.sys.tpw.keytest = 1, 测试完退出复位 persist.sys.tpw.keytest = 0;
+++ b/frameworks/base/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -3496,6 +3496,14 @@ public class PhoneWindowManager implements WindowManagerPolicy {
final boolean isDefaultDisplayOn = Display.isOnState(mDefaultDisplay.getState());
final boolean interactiveAndOn = interactive && isDefaultDisplayOn;
if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
+ // Modify add dispatch keycode_power tp app 2024/06/13 [s]
+ // https://blog.csdn.net/weixin_41028555/article/details/139437838
+ if (KeyEvent.KEYCODE_POWER == event.getKeyCode() && SystemProperties.getBoolean("persist.sys.tpw.keytest", false)) {
+ result |= ACTION_PASS_TO_USER;
+ Log.i(TAG, "mmi dispatch tp app, result = " + result);
+ return result;
+ }
+ // Modify add dispatch keycode_power tp app 2024/06/13 [e]
handleKeyGesture(event, interactiveAndOn);
}
如果需要包名或者类名拦截,可以参考以下获取包名和类名,替换判断属性值逻辑。
+++ b/frameworks/base/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -3496,6 +3496,14 @@ public class PhoneWindowManager implements WindowManagerPolicy {
final boolean isDefaultDisplayOn = Display.isOnState(mDefaultDisplay.getState());
final boolean interactiveAndOn = interactive && isDefaultDisplayOn;
if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
+ // Modify add dispatch keycode_power tp app 2024/06/13 [s]
+ // https://blog.csdn.net/weixin_41028555/article/details/139437838
+ String title = getTopPackage(mContext);
+ if (KeyEvent.KEYCODE_POWER == event.getKeyCode() && title != null && title.equals("com.android.ServiceMenu")) {
+ result |= ACTION_PASS_TO_USER;
+ Log.i(TAG, "mmi dispatch tp app, result = " + result);
+ return result;
+ }
+ // Modify add dispatch keycode_power tp app 2024/06/13 [e]
handleKeyGesture(event, interactiveAndOn);
}
public String getTopActivity(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
if (runningTaskInfos != null) {
return (runningTaskInfos.get(0).topActivity.getClassName());
} else {
return null;
}
}
public String getTopPackage(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
if (runningTaskInfos != null) {
return (runningTaskInfos.get(0).topActivity.getPackageName());
} else {
return null;
}
}