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) {
        }

 

發佈了86 篇原創文章 · 獲贊 101 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章