home键监听

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lamphogani/article/details/78340733
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();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Lamphogani/article/details/78340733