标签:
相比Home键(HOME)而近期应用的关键(APP_SWITCH)治,回车键很简单。复onKeyDown可以实现,如以下:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// KeyEvent.KEYCODE_HOME KeyEvent.KEYCODE_APP_SWITCH
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitAction();
return true;
} else
return super.onKeyDown(keyCode, event);
}
HOME和APP_SWITCH比較复杂,尤其是HOME键,假设不特殊设置。有可能会被恶意应用利用。
所以即使是处理了HOME键,实測会首先进入Launcher,一段时间后才会运行我们的操作,想必这也是系统层从安全角度的考量。有时间看一下系统源代码。
尝试过多种方式之后。复写onUserLeaveHint函数比較便捷。例如以下就可以:
@Override
protected void onUserLeaveHint() {
//super.onUserLeaveHint();
exitAction();
}
把操作写在了exitAction函数中,这里以启动设置为例:
private void exitAction() {
try {
Intent intent = new Intent();
ComponentName componentName = new ComponentName("com.android.settings",
"com.android.settings.Settings");
intent.setComponent(componentName);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
AndroidManifest.xml加权限:
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
Activity处理:
public class Main extends Activity {
public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
setContentView(R.layout.main);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// KeyEvent.KEYCODE_HOME KeyEvent.KEYCODE_APP_SWITCH
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)
return true;
else
return super.onKeyDown(keyCode, event);
}
}
Android中的Home Key,Power Key默认都是由系统的Framework来响应。假设想让自己的应用捕获响应,该怎么做呢?
Home Key比較简单,不涉及系统源代码改动:
getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
return true;
Power Key略微麻烦一些。要改动源代码:
1: 改动 phoneWindowManager.java 的 interceptKeyBeforeQueueing 方法,在參考行后增加:
case KeyEvent.KEYCODE_POWER: { // 參考行
result &= ~ACTION_PASS_TO_USER; // 參考行
// 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 ..");
}
//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; //原有代码
}
}
//增加行
版权声明:原创文章,转载请注明出处:http://blog.csdn.net/zhoumushui
标签:
原文地址:http://www.cnblogs.com/hrhguanli/p/4853660.html