Android 监听 home键和菜单键

Android 监听 home键和菜单键

代码粘贴过去就可以用了

// 创建方法注册广播
        registerReceiver(homeKeyEventReceiver, new IntentFilter(
                                Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

// 监听home键和菜单键
    private BroadcastReceiver homeKeyEventReceiver = new BroadcastReceiver() {
        String REASON = "reason";
        String HOMEKEY = "homekey";
        String RECENTAPPS = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(REASON);
                if (TextUtils.equals(reason, HOMEKEY)) {
                    // 点击 Home键
                    Toast.makeText(getApplicationContext(), "Home", 1).show();
                } else if (TextUtils.equals(reason, RECENTAPPS)) {
                    // 点击 菜单键
                    Toast.makeText(getApplicationContext(), "菜单键", 1).show();
                }
            }
        }
    };
//销毁方法里面记得反注册
        try {
            unregisterReceiver(homeKeyEventReceiver);
        } catch (Exception e) {
        }

 

你可能感兴趣的:(Android)