直接上代码

public class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {
    private String TAG = "TagForHomeKeyEventBroadCastReceiver";
    static final String SYSTEM_REASON = "reason";
    static final String SYSTEM_HOME_KEY = "homekey";
    static final String SYSTEM_RECENT_APPS = "recentapps";
    private boolean isRegisterReceiver = false;

    @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_REASON);
            if (reason != null) {
                if (reason.equals(SYSTEM_HOME_KEY)) {
                    // home key处理点
                    Log.i(TAG, "点击了Home键");
                } else if (reason.equals(SYSTEM_RECENT_APPS)) {
                    // long home key处理点
                    Log.i(TAG, "长按了Home键");
                }
            }
        }
    }

    /**
     * 广播注册
     *
     * @param mContext 上下文对象
     */
    public void register(Context mContext) {
        if (!isRegisterReceiver) {
            isRegisterReceiver = true;
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            mContext.registerReceiver(HomeKeyEventBroadCastReceiver.this, filter);
        }
    }

    /**
     * 广播注销
     *
     * @param mContext 上下文对象
     */
    public void unRegisterScreenActionReceiver(Context mContext) {
        if (isRegisterReceiver) {
            isRegisterReceiver = false;
            mContext.unregisterReceiver(HomeKeyEventBroadCastReceiver.this);
        }
    }
}
HomeKeyEventBroadCastReceiver receiver = new HomeKeyEventBroadCastReceiver();
// 注册
receiver.register(this);

// 注销
receiver.unRegisterScreenActionReceiver(this);
最后修改:2020 年 10 月 23 日 04 : 41 PM
如果觉得我的文章对你有用,请随意赞赏