Android 监听Home key

Android 应用对于Home键的监听不是那么容易,因为Home键可以将程序退出放在后台,所以这个事件是直接分发给系统,系统接收到之后做相应处理,Home键的事件不是直接传递到应用里面.所以不可以像在应用监听Back键那样(override Activity的 onkeydown)的方法监听Home.

下面提供一种监听Home的实现方式:

public class HomeWatcher {
   
   static final String TAG = "HomeWatcher";
   private Context mContext;
   private IntentFilter mFilter;
   private OnHomePressedListener mListener;
   
   private InnerReceiver mReceiver;
   
   public interface OnHomePressedListener
   {
      public void onHomePressed();
      public void onHomeLongPressed();
   }
   
   public HomeWatcher(Context context)
   {
      mContext = context;
      mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
   }

   public void setOnHomePressedListener(OnHomePressedListener listener)
   {
      mListener = listener;
      mReceiver = new InnerReceiver();
   }
   
   public void startWatch()
   {
      if(mReceiver != null)
      {
         mContext.registerReceiver(mReceiver, mFilter);
      }
   }
   
   public void stopWatch()
   {
      if(mReceiver != null)
      {
         mContext.unregisterReceiver(mReceiver);
      }
   }
   
   class InnerReceiver extends BroadcastReceiver
   {
      final String SYSTEM_DIALOG_REASON_KEY = "reason"; 
        final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions"; 
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"; 
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
        
        @Override 
        public void onReceive(Context context, Intent intent) {
         Log.d(TAG,"home key");
            String action = intent.getAction(); 
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { 
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY); 
                if (reason != null) { 
                    Log.e(TAG, "action:" + action + ",reason:" + reason); 
                    if (mListener != null) { 
                        if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) { 
                            // 短按home键 
                            mListener.onHomePressed(); 
                        } else if (reason 
                                .equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) { 
                            // 长按home键 
                            mListener.onHomeLongPressed(); 
                        } 
                    } 
                } 
            } 
        } 
      
   }
   
   
   
}

使用方式:
 
  
HomeWatcher homeWatcher = new HomeWatcher(mContext);
homeWatcher.setOnHomePressedListener( new HomeWatcher.OnHomePressedListener() { @Override public void onHomePressed() { Log. d( TAG, "onHomePressed"); } @Override public void onHomeLongPressed() { Log. d( TAG, "onHomeLongPressed"); }}); homeWatcher.startWatch();

结语,
采用动态注册广播的方式,经测这是一种行之有效的监听Home key 办法。


你可能感兴趣的:(Android)