原文链接:http://my.eoe.cn/viver120/archive/4276.html
一、Home键的扑捉
- Android4.0 版本以下时候处理:
1.1. 在AndroidManifest.xml中加上权限,禁止HOME键。
|
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
|
1.2 重载以下两个方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(KeyEvent.KEYCODE_HOME==keyCode){ //写要执行的动作或者任务 doSomething(); } return super.onKeyDown(keyCode, event); } @Override public void onAttachedToWindow(){ this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); }
|
- Android4.0以上的版本:
捕获系统日志。
如果我们留意观察就可以发现,当我们按下HOME键的时候,Logcat就会输出以下信息:
|
I/ActivityManager( 144): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.android.launcher/com.android.launcher2.Launcher } from pid 144
|
这样我们只要捕获logcat的信息就能监听到HOME键了。
- 加权限:
|
<uses-permission android:name="android.permission.READ_LOGS"/>
|
- 捕获logcat信息。启动线程监控,建议将线程的启动放到concrete()中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
//监听HOME键,听着音乐服务。 public void listenerHome() { new Thread(new Runnable() { public void run() { Process mLogcatProc = null; BufferedReader reader = null; try { /* 获取logcat信息 * logcat:日志类型为logcat * ActivityManager日志Tag为ActivityManager * I:<span style="font-size:16px;">logcat的标识分为:(V</span> :Verbose<span style="font-size:16px;"> D </span>:Debug<span style="font-size:16px;"> I</span> :Info<span style="font-size:16px;"> W</span> :Warning<span style="font-size:16px;"> E</span> :Error<span style="font-size:16px;"> * F</span> :Fatal<span style="font-size:16px;"> S</span> :Silent)这里I代表Info。 * *:S:日志的所有内容 */ mLogcatProc = Runtime.getRuntime().exec( new String[] { "logcat", "ActivityManager:I *:S" }); reader = new BufferedReader(new InputStreamReader( mLogcatProc.getInputStream())); String line; while ((line = reader.readLine()) != null) { if (line.indexOf("android.intent.category.HOME") > 0) { Looper.prepare(); //bgmusic_playler.stop(); //捕获到HOME键后发送message,在handler中可以自主处理。 handler.sendMessage(handler.obtainMessage()); Runtime.getRuntime().exec("logcat -c"); Looper.loop(); break; } } } catch (Exception e) { e.printStackTrace(); } } }).start(); }
|
二、Home键的屏蔽
android4.0 以上的版本屏蔽HOME按键有个方便的方法,如下三步:
-
定义静态常量:public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;
-
在oncreate()中的setContentView之前写一句代码:this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED,FLAG_HOMEKEY_DISPATCHED);
-
再重写onkey事件。
示例如下:
|
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); this.setContentView(R.layout.keys_test_layout); ......... }
|