home鍵監聽
阿新 • • 發佈:2018-11-27
public class BaseActivity extends Activity { private HomeWatcherReceiver mHomeWatcherReceiver = null; private boolean isNeedFinish = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(); } private void registerReceiver() { mHomeWatcherReceiver = new HomeWatcherReceiver(); IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mHomeWatcherReceiver, filter); } public class HomeWatcherReceiver extends BroadcastReceiver { private static final String SYSTEM_DIALOG_REASON_KEY = "reason"; private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"; @Override public void onReceive(Context context, Intent intent) { String intentAction = intent.getAction(); //L.e("intentAction =" + intentAction); if (TextUtils.equals(intentAction, Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY); //L.e("reason =" + reason); if (TextUtils.equals(SYSTEM_DIALOG_REASON_HOME_KEY, reason)) { L.e("按下了home鍵"); if (!spUtil.getFromSp("home_down_back", false)) { spUtil.saveToSp("home_down_back", true); } } } } } @Override protected void onResume() { super.onResume(); if (spUtil.getFromSp("home_down_back", false)) {//防止activity之間跳轉的時候走這裡 L.e("home down back"); spUtil.saveToSp("home_down_back", false); } } @Override protected void onDestroy() { super.onDestroy(); if (mHomeWatcherReceiver != null) { try { unregisterReceiver(mHomeWatcherReceiver); } catch (Exception e) { e.printStackTrace(); } } } }