Android中各種訊息監聽機制
阿新 • • 發佈:2019-02-03
1、Boadcast, receiverboadcast:sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));receiver:IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED); context.registerReceiver(mBroadcastReceiver, filter);處理: private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action) || Intent.ACTION_SCREEN_OFF.equals(action)) { String reason = intent.getStringExtra(PhoneWindowManager.SYSTEM_DIALOG_REASON_KEY); if (!PhoneWindowManager.SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS.equals(reason)) { mHandler.sendEmptyMessage(MESSAGE_DISMISS); } } else if (TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED.equals(action)) { // Airplane mode can be changed after ECM exits if airplane toggle button // is pressed during ECM mode if (!(intent.getBooleanExtra("PHONE_IN_ECM_STATE", false)) && mIsWaitingForEcmExit) { mIsWaitingForEcmExit = false; changeAirplaneModeSystemSetting(true); } } } };2、register listener本質是通過binder機制得以實現的一種註冊與回撥關係。註冊listener進service的通知佇列: TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE);當事件發生時,DefaultPhoneNotifier通過binder回撥mPhoneStateListener.callback. r.callback.onServiceStateChanged(new ServiceState(state));處理:PhoneStateListener mPhoneStateListener = new PhoneStateListener() { @Override public void onServiceStateChanged(ServiceState serviceState) { if (!mHasTelephony) return; //[email protected] fix bug:10207 //final boolean inAirplaneMode = serviceState.getState() == ServiceState.STATE_POWER_OFF; final boolean inAirplaneMode = Settings.Global.getInt( mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) == 1; mAirplaneState = inAirplaneMode ? ToggleAction.State.On : ToggleAction.State.Off; mAirplaneModeOn.updateState(mAirplaneState); mAdapter.notifyDataSetChanged(); } };3、ContentObserver這是一種監聽資料庫變化來產生響應的監聽機制註冊:mContext.getContentResolver().registerContentObserver( Settings.Global.getUriFor(Settings.Global.AIRPLANE_MODE_ON), true, mAirplaneModeObserver);)處理: private ContentObserver mAirplaneModeObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { onAirplaneModeChanged(); } };