項目更新到9.0後,靜态注冊的自定義廣播無法接收,需要改為動态注冊;此外,接收到開機廣播和點選運作APP(被強制停止後再次啟動)時都需要注冊,需要避免重複注冊。
避免重複注冊的方法借鑒了單例模式,代碼如下:public static class TaskBroadcast extends BroadcastReceiver {
private TaskBroadcast()
{
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(POLL_START_TIMER_BC);
MyApplication.getContext().registerReceiver(this, intentFilter);
Log.e(TAG, "TaskBroadcast create");
}
private static TaskBroadcast receiver = null;
private static class innerc{
static TaskBroadcast receiver = new TaskBroadcast();
}
public static void registerTaskBroadCast() {
Log.w(TAG, "registerTaskBroadCast");
receiver = innerc.receiver;
return;
}
public static void unRegisterTaskBroadCast() {
Log.w(TAG, "unRegisterTaskBroadCast");
if (receiver != null) {
MyApplication.getContext().unregisterReceiver(receiver);
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w(TAG, "taskBroadcast:" + action);
if (POLL_START_TIMER_BC.equals(action)){
startPoll(context, null);
}
}
}
内部類innerc的靜态變量receiver隻會初始化一次,是以構造函數TaskBroadcast()隻會執行一次。