Android 普通键值可以直接在dispatchKeyEvent()中处理,但锁屏键、Home键不可以,比较特殊,需要单独监听其广播,且必须为动态广播,其静态广播无效;
public class BaseActivity extends Activity {
@Override public void onStart() { super.onStart(); registerHomeKeyReceiver(); }@Override public void onStop() { super.onStop(); unregisterHomeKeyReceiver(); } private void registerHomeKeyReceiver() { mHomeKeyReceiver = new HomeKeyEventBroadCastReceiver(); IntentFilter homeKeyFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mHomeKeyReceiver, homeKeyFilter); } private void unregisterHomeKeyReceiver() { if (mHomeKeyReceiver != null) { try { unregisterReceiver(mHomeKeyReceiver); } catch (Exception e) { e.printStackTrace(); } } } }
public class HomeKeyEventBroadCastReceiver extends BroadcastReceiver { static final String SYSTEM_REASON = "reason"; static final String SYSTEM_HOME_KEY = "homekey";//home key @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 (reason != null) { if (reason.equals(SYSTEM_HOME_KEY)) { // home key处理 context.startService(new Intent(context, ADTimeService.class)); } } } } }