我有一个问题,我的BroadcastReceiver
已多次注册。
我的应用在CountDownTimer
对象中有一个Application
。它在这个类中的原因是因为一旦它被启动,用户应该能够在倒计时时移动到其他活动。
CountDownTimer
倒计时后,我会启动LocalBroadcast
,其中Activity
已注册接收。
除了onReceive
之外,一切正常都被称为倍数倍。例如,如果用户在Activity1中启动CountDownTimer
,则移至Activity2,然后返回到Activity1,调用onReceive
两次。
活动的launchMode
设置为SingleInstance
,noHistory
设置为true
。这是我尝试只有一个注册活动的实例,并希望有一个接收者。
这是CountDownTimer
对象中的Application
:
public static void startLoneworkerCountDownTimer(int duration){
long durationInMillis = duration * 60 * 1000;
cdt = null;
cdt = new CountDownTimer(durationInMillis, 1000) {
public void onTick(long millisUntilFinished) {
setLoneWorkerCountDownTimerRunning(true);
int secs = (int) (millisUntilFinished / 1000);
int mins = secs / 60;
secs = secs % 60;
// int milliseconds = (int) (millisUntilFinished % 1000);
loneWorkerTimerValue = mins + ":" + String.format("%02d", secs);
//tvCountDown.setText(timerValue);
}
public void onFinish() {
setLoneWorkerCountDownTimerRunning(false);
loneWorkerTimerValue = "0:00";
Log.e(TAG, "LoneWorker Timer is done.");
LocalBroadcastManager.getInstance(mContext).sendBroadcast(new LoneworkerCountdownFinishedIntent());
}
}.start();
}
这是我初始化,注册和取消注册我的接收器的方式:
public void unRegisterCountDownFinishedReceiver(){
try {
unregisterReceiver(countDownFinishedreceiver);
} catch (Exception e) {}
}//end of unRegisterCountDownFinishedReceiver
public void initializeCountDownFinishedReceiver(){
if(countDownFinishedreceiver == null){
countDownFinishedreceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "inside onReceive in countDownFinishedreceiver");
//do something
}//end of onReceive
};
}
}//end of registerCountDownReceiver()
public void registerCountDownFinishedReceiver(){
Log.e(TAG, "about to register countDownFinishedreceiver!!!!!!!!!!!!!!!!!!!!!!!!***********!!!!!!!!!!!!");
LocalBroadcastManager.getInstance(this)
.registerReceiver(countDownFinishedreceiver,new IntentFilter(LoneworkerCountdownFinishedIntent.ACTION_COUNTDOWN_FINISHED));
}
这是我对LocalBroadcast
:
import android.content.Intent;
public class LoneworkerCountdownFinishedIntent extends Intent {
public static final String ACTION_COUNTDOWN_FINISHED = "com.xxxxx.countdownfinished";
public LoneworkerCountdownFinishedIntent() {
super(ACTION_COUNTDOWN_FINISHED);
}
}
在onCreate
{i}仅在CountDownTimer
班级中Application
正在运行时才拨打以下内容:
initializeCountDownFinishedReceiver();
registerCountDownFinishedReceiver();
我的问题是如何确保只在Receiver上注册?
我希望用户能够在CountDownTimer
运行时尽可能多地启动Activity,但只运行一个onReceive
。