Android app:如何让 App 拿到Power key 值
原文(有删改):https://blog.csdn.net/qq_37858386/article/details/103835664
介绍
默认机制:Power key 通常都是由 framework 自行的 处理的, app 无法拿到这个 key 值的。
修改
Framework
路径:frameworksaseservicescorejavacomandroidserverpolicyPhoneWindowManager.java
PhoneWindowManager
主要用于实现各种实体或虚拟按键处理。
修改interceptKeyBeforeQueueing
方法,把case KeyEvent.KEYCODE_POWER
部分做如下修改:
其中,
com.example.keyeventdemo
是需要获取power事件app的包名:
case KeyEvent.KEYCODE_POWER: {
Log.d(TAG,"detect power key in special package, pass to user! "+KeyEvent.KEYCODE_POWER);
result &= ~ACTION_PASS_TO_USER;
// add-start
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
try{
if (activityManager.getRunningTasks(1).get(0).topActivity.getPackageName().equals("com.example.keyeventdemo")){
//Please reset the special package name.
result |= ACTION_PASS_TO_USER;
Log.d(TAG,"detect power key in special package, pass to user!");
}
}catch(NullPointerException e){
Log.d(TAG,"ingore a NullPointerException ..");
}
// add-end
// others code
}
app
三、实际测试ok,按下power键没有灭屏幕,app获取到该事件。
四、app测试代码
public class MainActivity extends AppCompat Activity {
private Textview key_result;
private String desc = "";
@0verride
protected void onCreate(Bundle savedInst anceSt ate) {
super.onCreate(savedInstanceState);
setCont entView(R.1ayout.activity_main);
key_result =(TextView) findViewById(R. id.key_result);
@0verride
public boolean onKeyDown(int keyCode,KeyEvent event) {
desc = String.format("%sphysical key coce is %i", desc, keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK)
{
desc = String.format("%s,KEYCODE BACK",desc);
} else if (keyCode == KeyEvent.KEYCODE_MENU ) {
desc = String.format("%s,KEYCODE_MEN",desc);
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP);{
desc = String.format("%s, KEYCODE_VOLUME_UP", desc);
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWD){
desc = String.format("%s,KEYCODE_VOLUME_DOWN", desc);
}else if (keyCode == KeyEvent. KEYCODE_POWER){
desc = String.format("%s, KEYCODE_POWER", desc);
}else {
desc = String.format("%s, KEYCODE_VOLUME is unknown", desc);
}
desc = desc + "
";
key_result.set Text (desc) ;
//返回true表示不再响应系统动作,返回false表示继续响应系统动作return true;
// return false:
}
}
}