前言
欢迎大家我分享和推荐好用的代码段~~
声明
欢迎转载,但请保留文章原始出处:
CSDN:http://www.csdn.net
雨季o莫忧离:http://blog.csdn.net/luckkof
正文
Power key 通常都是由 framework 自行的
app 无法拿到这个 key 值
如果想让某个 app 自行处理 power key
应该要怎么做呢?
1: 修改 phoneWindowManager.java 的 interceptKeyBeforeQueueing 方法,在 reference line 后加入下面这段代码
case KeyEvent.KEYCODE_POWER: { //reference line
result &= ~ACTION_PASS_TO_USER; //reference line
case KeyEvent.KEYCODE_POWER: { //reference line
result &= ~ACTION_PASS_TO_USER; //reference line
// add begin
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
try{
if (activityManager.getRunningTasks(1).get(0).topActivity.getPackageName().equals("your_special_package_name")){
//Please reset the special package name.
result |= ACTION_PASS_TO_USER;
Xlog.d(TAG,"detect power key in special package, pass to user!")
}
}catch(NullPointerException e){
Xlog.d(TAG,"ingore a NullPointerException ..");
}
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
try{
if (activityManager.getRunningTasks(1).get(0).topActivity.getPackageName().equals("your_special_package_name")){
//Please reset the special package name.
result |= ACTION_PASS_TO_USER;
Xlog.d(TAG,"detect power key in special package, pass to user!")
}
}catch(NullPointerException e){
Xlog.d(TAG,"ingore a NullPointerException ..");
}
//add end
2: 同样在此分支内, 找到 else 语句段, 并找到如下位置加入
if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) { //参考行
if(!((result & ACTION_PASS_TO_USER) == ACTION_PASS_TO_USER)){ //加入行
result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP; //原有代码
} //加入行
}
if(!((result & ACTION_PASS_TO_USER) == ACTION_PASS_TO_USER)){ //加入行
result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP; //原有代码
} //加入行
}
注意: 以上蓝色背景部分的内容需要替换为您预期要处理 power key 的 app 对应的 package name.