Android 通过广播接听Home键,这个方式是比较好用的一种方式
1.自定义广播
public class BroadcastReceiverEx extends BroadcastReceiver{ String SYSTEM_REASON = "reason"; String SYSTEM_HOME_KEY = "homekey"; String SYSTEM_HOME_KEY_LONG = "recentapps"; @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 (TextUtils.equals(reason, SYSTEM_HOME_KEY)) { //按了home键 Constants.isHome = true; //ToastUtil.showToast(context, "按了home键" + isHome); }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){ //长按home键,显示最近使用的程序列表 } } } }
2.注册广播
//HOME键监听注册 registerReceiver(new BroadcastReceiverEx(), new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
3.按了Home键之后你想进行的操作
@Override protected void onRestart() { super.onRestart(); if (Constants.isHome) { // ToastUtil.showToast(context, ""+Constants.isHome); Constants.isHome = false; //按了HOME键重启的操作 } }
4,判断是否是按了Home键
/** 监听HOME键 */ public static boolean isHome = false;
5.解除注册 (我是在Application中注册的所以我到onLowMemory中解除注解)
@Override public void onLowMemory() { // TODO Auto-generated method stub super.onLowMemory(); unregisterReceiver(broadcastReceiverEx); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-03 21:06:12