問題
需要全局接收廣播官硝,因此使用的LocalBroadcastManager
目前出現(xiàn)的問題時(shí)界面重復(fù)進(jìn)入聋亡,會(huì)導(dǎo)致廣播重復(fù)注冊(cè)與接收
出現(xiàn)原因
一般這種情況的出現(xiàn)原因廣播多次注冊(cè)或者重復(fù)注冊(cè)
解決辦法
網(wǎng)上大部分都是說出現(xiàn)原因委煤,但并沒有一個(gè)具體的解決方案
我的思路是判斷當(dāng)前廣播是否注冊(cè)康铭,保證只注冊(cè)一次,這里利用反射實(shí)現(xiàn)
判斷當(dāng)前廣播是否注冊(cè)披粟,代碼如下:
/**
*
* action IntentFilter中的某一個(gè)action咒锻,因?yàn)楂@取到的是IntentFilter的所有action,所以只要匹配一個(gè)就可以
*
*/
private boolean isRegister(LocalBroadcastManager manager,String action) {
boolean isRegister = false;
try {
Field mReceiversField = manager.getClass().getDeclaredField("mReceivers");
mReceiversField.setAccessible(true);
// String name = mReceiversField.getName();
HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers = (HashMap<BroadcastReceiver, ArrayList<IntentFilter>>) mReceiversField.get(manager);
for (BroadcastReceiver key : mReceivers.keySet()) {
ArrayList<IntentFilter> intentFilters = mReceivers.get(key);
MyLogUtil.e("Key: " + key + " Value: " + intentFilters);
for (int i = 0; i < intentFilters.size(); i++) {
IntentFilter intentFilter = intentFilters.get(i);
Field mActionsField = intentFilter.getClass().getDeclaredField("mActions");
mActionsField.setAccessible(true);
ArrayList<String> mActions = (ArrayList<String>) mActionsField.get(intentFilter);
for (int j = 0; j < mActions.size(); j++) {
if (mActions.get(i).equals(action)) {
isRegister = true;
break;
}
}
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return isRegister;
}
使用方式:
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
isRegister = isRegister(manager, mActions);
if (!isRegister) {
manager.registerReceiver(mLocalReceiver, mIntentFiiter);
}
原創(chuàng)作品守屉,允許轉(zhuǎn)載惑艇,轉(zhuǎn)載時(shí)請(qǐng)務(wù)必以超鏈接形式標(biāo)明文章 原始出處 、作者信息和本聲明拇泛。