本來是在實(shí)驗(yàn)通過廣播來獲取系統(tǒng)狀態(tài)的功能的. 偶然間發(fā)現(xiàn)還有LocalBoardcast這個東西 -_- 真汗顏.
趕緊惡補(bǔ)一下..
摘自網(wǎng)絡(luò)博客:
在android-support-v4.jar中引入了LocalBroadcastManager,稱為局部通知管理器,這種通知的好處是安全性高,效率也高,適合局部通信,可以用來代替Handler更新UI
現(xiàn)在總結(jié)一下主要使用流程.(相當(dāng)簡單)
用代碼表示了.
(1) 設(shè)定一個廣播
private ConnectivityManager mConnectivityManager = null;
private NetworkInfo mNetworkInfo = null;
private BroadcastReceiver mNetworkBoardcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null) {
return;
}
// Log.d(logTitle, "onReceive: some boardcast" + intent.toString());
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mConnectivityManager = (ConnectivityManager) getSystemService(Context
.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
if (mNetworkInfo.getTypeName().equals("WIFI")) {
sendNetworkStateBoardcast(ACTION_CONNECTIONED);
Log.d(logTitle, "netstate to:" + mNetworkInfo.getTypeName());
} else {
sendNetworkStateBoardcast(STATE_NETWORK_MOBILE);
Log.d(logTitle, "netstate to:" + mNetworkInfo.getTypeName());
}
} else {
sendNetworkStateBoardcast(ACTION_NO_CONNECTION);
}
}
}
};
private void sendNetworkStateBoardcast(String state) {
Intent sendIntent = new Intent(state);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(sendIntent);
}
(2) 設(shè)定廣播接收器
public class BoardcastReceiverDetectSystemStatus extends BroadcastReceiver {
Context currentContext;
public BoardcastReceiverDetectSystemStatus() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d("broadreveiver", "onReceive: intent is" + intent.toString());
}
}
(3) activity內(nèi)設(shè)定本地廣播接收
boardcastReceiverDetectSystemStatus = new BoardcastReceiverDetectSystemStatus(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ServiceDetectSystemStatus.ACTION_CONNECTIONED);
intentFilter.addAction(ServiceDetectSystemStatus.ACTION_NO_CONNECTION);
LocalBroadcastManager.getInstance(this).registerReceiver(boardcastReceiverDetectSystemStatus, intentFilter);
以上就是三個主要步驟, 當(dāng)然, 后期可以根據(jù)需要進(jìn)行二次封裝以及改造. 去耦
官方文檔:
https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html