本文实例讲述了Android监听Home键的方法。分享给大家供大家参考,具体如下:
将到android中Home键的监听,很多人第一反应时重写相应Activity的onKeyDown()方法,监听当按下的键的keyCode为KEYCODE_HOME时,进行自己的相应的处理。如:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
stopService(mIntentService);
return true;
}
return super.onKeyDown(keyCode, event);
}
但是这样的监听是不能监听到HOME键的。这样的方法只能监听到BACK,MENU键。那么怎么监听Home键了?
1.新建一个监听Home键的Listener
public class HomeListener {
static final String TAG = "HomeListener";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
// 回调接口
public interface OnHomePressedListener {
public void onHomePressed();
public void onHomeLongPressed();
}
public HomeListener(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
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) {
// Log.e(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();
}
}
}
}
}
}
}
2.在使用的类的onCreate方法中注册Home键的监听
private void registerHomeListener() {
mHomeWatcher = new HomeListener(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
@Override
public void onHomePressed() {
//TODO 进行点击Home键的处理
Log.i("xsl", "0000000000000");
stopService(mIntentService);
}
@Override
public void onHomeLongPressed() {
//TODO 进行长按Home键的处理
Log.i("xsl", "0000000000000");
}
});
mHomeWatcher.startWatch();
}
3.在使用的类的onPause方法中停止监听
mHomeWatcher.stopWatch();
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android资源操作技巧汇总》、《Android视图View技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。
您可能感兴趣的文章:Android 解决监听home键的几种方法Android监听home键的方法详解Android4.0.x Home键事件拦截监听的方法Android监听Home键和Back键的区别介绍Android中监听Home键的4种方法总结