Android Home键按键事件监听

来源:互联网 发布:stc单片机的J什么意思 编辑:程序博客网 时间:2024/05/16 00:59

    平时用的比较多的是Back键按键的监听,但是后来修改相机问题时遇到了需要监听Home键的情况,遂各种搜索资料,get到如下技能:

    Home键的监听也需要注册广播接收器(采用动态注册的方式),通过拦截让窗口关闭的系统动作,然后根据Intent里面的具体参数来判断是否为Home键点击事件。

    接收器代码:

    

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class HomeWatcherReceiver extends BroadcastReceiver {    private static final String LOG_TAG = "HomeReceiver";    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();        Log.i(LOG_TAG, "onReceive: action: " + action);        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {            // android.intent.action.CLOSE_SYSTEM_DIALOGS            String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);            Log.i(LOG_TAG, "reason: " + reason);            if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {                // 短按Home键                Log.i(LOG_TAG, "homekey");            }            else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {                // 长按Home键 或者 activity切换键                Log.i(LOG_TAG, "long press home key or activity switch");            }            else if (SYSTEM_DIALOG_REASON_LOCK.equals(reason)) {                // 锁屏                Log.i(LOG_TAG, "lock");            }            else if (SYSTEM_DIALOG_REASON_ASSIST.equals(reason)) {                // 长按Home键                Log.i(LOG_TAG, "assist");            }        }    }}

   动态注册代码:

    

private static HomeWatcherReceiver mHomeKeyReceiver = null;    private static void registerHomeKeyReceiver(Context context) {        Log.i(LOG_TAG, "registerHomeKeyReceiver");        mHomeKeyReceiver = new HomeWatcherReceiver();        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);        context.registerReceiver(mHomeKeyReceiver, homeFilter);    }    private static void unregisterHomeKeyReceiver(Context context) {        Log.i(LOG_TAG, "unregisterHomeKeyReceiver");        if (null != mHomeKeyReceiver) {            context.unregisterReceiver(mHomeKeyReceiver);        }    }

    在Activity的onPause()和onResume()里面分别调用:

    

@Override    protected void onResume() {        super.onResume();        registerHomeKeyReceiver(this);    }    @Override    protected void onPause() {        unregisterHomeKeyReceiver(this);        super.onPause();    }

    参考地址:http://www.cnblogs.com/mengdd/p/3951223.html

0 0
原创粉丝点击