android的Home键的监听封装工具类(一)

android的Home键的监听封装:

 1 package com.gzcivil.utils;
 2 
 3 import android.content.BroadcastReceiver;
 4 import android.content.Context;
 5 import android.content.Intent;
 6 import android.content.IntentFilter;
 7 
 8 /**
 9  * Home键监听封装
10  * 
11  */
12 public class HomeListener {
13 
14     static final String TAG = "HomeListener";
15     private Context mContext;
16     private IntentFilter mFilter;
17     private OnHomePressedListener mListener;
18     private InnerRecevier mRecevier;
19 
20     // 回调接口
21     public interface OnHomePressedListener {
22         public void onHomePressed();
23         public void onHomeLongPressed();
24     }
25 
26     public HomeListener(Context context) {
27         mContext = context;
28         mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
29     }
30 
31     /**
32      * 设置监听
33      * 
34      * @param listener
35      */
36     public void setOnHomePressedListener(OnHomePressedListener listener) {
37         mListener = listener;
38         mRecevier = new InnerRecevier();
39     }
40 
41     /**
42      * 开始监听,注册广播
43      */
44     public void startWatch() {
45         if (mRecevier != null) {
46             mContext.registerReceiver(mRecevier, mFilter);
47         }
48     }
49 
50     /**
51      * 停止监听,注销广播
52      */
53     public void stopWatch() {
54         if (mRecevier != null) {
55             mContext.unregisterReceiver(mRecevier);
56         }
57     }
58 
59     /**
60      * 广播接收者
61      */
62     class InnerRecevier extends BroadcastReceiver {
63         final String SYSTEM_DIALOG_REASON_KEY = "reason";
64         final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
65         final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
66         final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
67 
68         @Override
69         public void onReceive(Context context, Intent intent) {
70             String action = intent.getAction();
71             if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
72                 String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
73                 if (reason != null) {
74                     // Log.e(TAG, "action:" + action + ",reason:" + reason);
75                     if (mListener != null) {
76                         if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
77                             // 短按home键
78                             mListener.onHomePressed();
79                         } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
80                             // 长按home键
81                             mListener.onHomeLongPressed();
82                         }
83                     }
84                 }
85             }
86         }
87     }
88 }

 

posted @ 2016-02-01 10:42  LiJinlun  阅读(352)  评论(0编辑  收藏  举报