在Android項目開發的過程當中,會較頻繁地使用到廣播,下面將廣播的基本代碼分享以下java
/* 發送廣播 */ private void sendBroadCast() { Intent intent = new Intent(Constants.SEND_DYNAMIC_CHANGE_ACTION)//參數是action的值 mContext.sendBroadcast(mIntent); }
/* 接收廣播 */ private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context context,Intent intent) { String action = intent.getAction(); if(action.equals(Constants.SEND_DYNAMIC_CHANGE_ACTION)) { //執行廣播要處理的內容 } } }
/* 註冊廣播 */ private void regesiterVroadcast() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Constants.SEND_DYNAMIC_CHANGE_ACTION); if(mBroadcastReceiver != null) { mContext.regesiterReceiver(mBroadcastReceiver,intentFilter); } }
/* 關閉廣播 */ if(mBroadcastReceiver != null) { mContext.unregesiterReceiver(mBroadcastReceiver);//關閉廣播 }