Android 監聽home鍵的動作

童思宇發表於2018-02-05

1.自定義一個類,繼承自BroadcastReceiver

/**
 * 監聽按下home鍵動作的廣播
 */
class HomeReceiver extends BroadcastReceiver {

    private final String SYSTEM_DIALOG_REASON_KEY = "reason";
    private final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d(TAG, "onReceive: is home");
        String action = intent.getAction();

        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            Log.d(TAG, "onReceive: action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)");
            String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
            Log.d(TAG, "onReceive: reason == " + reason);

            if (null == reason) {
                Log.d(TAG, "onReceive: null == reason");
                return;
            }

            //home            if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                Log.d(TAG, "onReceive: reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)");
                try {
                    if (null != mCarPlayService) {
                        int key = mCarPlayService.sendKey(2, true);
                        Log.d(TAG, "honeKey is " + key);
                    } else {
                        Log.d(TAG, "onReceive: null == mCarPlayService");
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                clickHomeListener();
            } else {
                Log.d(TAG, "onReceive: reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY) is not");
            }
        } else {
            Log.d(TAG, "onReceive: action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS) is not");
        }
    }
}
2.註冊監聽

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Log.d(TAG, "onActivityCreated: ");
    mActivity = getActivity();

    mHomeReceiver = new HomeReceiver();
    IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    mActivity.registerReceiver(mHomeReceiver, homeFilter);}
3.解除監聽

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy: ");
    mActivity.unregisterReceiver(mHomeReceiver);
}

相關文章