网上看到demo,亲测了以下机器和设备,均测试通过:
测试通过的手机:
1.华为荣耀3(Android 4.2.2)
2.小米2s(Android 4.1.1)
3.联想的手机 (Android2.3.5)
4.Google Nexus 5模拟器(Android 4.4.2)
核心代码:
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; public class HomeWatcher { static final String TAG = "wxl"; 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; mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); } /** * 设置监听 * * @param listener */ 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(); } } } } } } }
调用方式:
public class MainActivity extends Activity { private static final String TAG = "wxl"; private HomeWatcher mHomeWatcher; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHomeWatcher = new HomeWatcher(this); mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() { @Override public void onHomePressed() { Toast.makeText(MainActivity.this, "onHomePressed", Toast.LENGTH_LONG).show(); } @Override public void onHomeLongPressed() { Toast.makeText(MainActivity.this, "onHomeLongPressed", Toast.LENGTH_LONG).show(); } }); mHomeWatcher.startWatch(); } /** * 重新进入或打开屏幕灯 */ protected void onRestart() { Log.d(TAG, "onRestart"); mHomeWatcher.startWatch(); super.onRestart(); } /** * 按Home键或关闭屏幕灯 */ protected void onPause() { super.onPause(); Log.d(TAG, "onPause"); mHomeWatcher.stopWatch();// 在onPause中停止监听,不然会报错的。 } }