监听Android 的home键[转]

转自:here

常常需要监听android HOME键,当HOME键下压时,往往需要做一些状态保存,音效停止等操作,那么如何做,才能监听到HOME键呢?我们知道HOME是系统键,app中无法通过onKey这些函数来处理。要妥善的处理HOME键,首先需要看看HOME键下压时,系统做了些什么。

二、app中对于HOME键广播事件的接收

      首先,自定义一个BroadcastReceiver:

 1     class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {
 2 
 3         static final String SYSTEM_REASON = "reason";
 4         static final String SYSTEM_HOME_KEY = "homekey";//home key
 5         static final String SYSTEM_RECENT_APPS = "recentapps";//long home key
 6         
 7         @Override
 8         public void onReceive(Context context, Intent intent) {
 9             String action = intent.getAction();
10             if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
11                 String reason = intent.getStringExtra(SYSTEM_REASON);
12                 if (reason != null) {
13                     if (reason.equals(SYSTEM_HOME_KEY)) {
14                         // home key处理点
15                         
16                     } else if (reason.equals(SYSTEM_RECENT_APPS)) {
17                         // long home key处理点
18                     }
19                 }
20             }
21         }
22     }

其次,生成且注册之

1         receiver = new HomeKeyEventBroadCastReceiver();
2         registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
posted @ 2014-07-22 16:12  王自强  阅读(193)  评论(0编辑  收藏  举报