您的位置:首页 > 移动开发 > Android开发

Android Home键监听

2013-11-19 14:50 357 查看
Home键监听:

1. 在onResum里面注册广播,OnPause里面注销广播。

2. 再广播中拦截Intent.ACTION_CLOSE_SYSTEM_DIALOGS 这个Action ,通过获取Reason字段 来判断长按 还是单击Home键。

下面看看代码:

package com.way.common.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

/**
* Home键监听封装
*
* @author way
*
*/
public class HomeWatcher {

static final String TAG = "HomeWatcher";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;

// 回调接口
public interface OnHomePressedListener {
public void onHomePressed();

public void onHomeLongPressed();
}

public HomeWatcher(Context context) {
mContext = context;
mRecevier = new InnerRecevier();
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}

/**
* 设置监听
*
* @param listener
*/
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
}

/**
* 开始监听,注册广播
*/
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}

/**
* 停止监听,注销广播
*/
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}

/**
* 广播接收者
*/
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

@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_DIALOG_REASON_KEY);
if (reason != null) {
L.i(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
// 短按home键
mListener.onHomePressed();
} else if (reason
.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
// 长按home键
mListener.onHomeLongPressed();
}
}
}
}
}
}
}

然后再Activity中重写OnResum方法

@Override
protected void onResume() {
// TODO Auto-generated method stub
mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(this);
mHomeWatcher.startWatch();
super.onResume();
}


再Onpause方法里面注销监听

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mHomeWatcher.setOnHomePressedListener(null);
mHomeWatcher.stopWatch();
}

在Activity中实现OnHomePressedListener接口,我们就可以在实现方法里面做我们自己的操作了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: