HOME键监听

Android 虽然可以通过重写 OnKeyDown() 方法来监听系统按键事件,但却接收不到 Home 键事件,这是因为 Home 键将程序退至后台,将这个事件分发给系统,再由系统进行相应的处理,所以在应用中是接收不到该事件的。为此 Android 提供了一种方法:通过广播接收者的方式来解决 Home 键的监听问题。

1. 创建广播接收者

public class KeyReceiver extends BroadcastReceiver {

    private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
    private static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
    private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
    private static final String SYSTEM_DIALOG_REASON_LOCK = "lock";
    private static final String SYSTEM_DIALOG_REASON_ASSIST = "assist";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
            if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
                //短按Home键
            } else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {
                //长按Home键或Activity切换键
            } else if (SYSTEM_DIALOG_REASON_LOCK.equals(reason)) {
                //锁屏
            } else if (SYSTEM_DIALOG_REASON_ASSIST.equals(reason)) {
                //SamSung长按Home键
            }
        }
    }
}

2. 动态注册并及时注销广播

动态注册广播

KeyReceiver mReceiver = new KeyReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(mReceiver, filter);

注销广播

if (mReceiver != null) {
    unregisterReceiver(mReceiver);
}

你可能感兴趣的:(Android开发)