Android 多次执行的广播接收机
我有一个问题,我的Android 多次执行的广播接收机,android,android-broadcastreceiver,Android,Android Broadcastreceiver,我有一个问题,我的BroadcastReceiver注册了好几次 我的应用程序在Application对象中有一个CountDownTimer。它之所以在这个类中,是因为一旦它被启动,用户应该能够在倒计时时移动到其他活动 一旦倒计时倒计时,我就启动一个本地广播,某个活动被注册接收 除了接收时的onReceive被称为倍数外,一切正常。例如,如果用户在Activity1中启动倒计时,然后移动到Activity2,然后返回到Activity1,则会调用两次onReceive 活动的launchMod
BroadcastReceiver
注册了好几次
我的应用程序在Application
对象中有一个CountDownTimer
。它之所以在这个类中,是因为一旦它被启动,用户应该能够在倒计时时移动到其他活动
一旦倒计时
倒计时,我就启动一个本地广播
,某个活动
被注册接收
除了接收时的onReceive
被称为倍数外,一切正常。例如,如果用户在Activity1中启动倒计时
,然后移动到Activity2,然后返回到Activity1,则会调用两次onReceive
活动的launchMode
设置为SingleInstance
,noHistory
设置为true
。这是我试图只拥有一个注册活动的实例,希望只有一个接收者
这是我在应用程序
对象中的倒计时:
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
中,仅当CountDownTimer
在应用程序
类中运行时,我才调用以下命令:
initializeCountDownFinishedReceiver();
registerCountDownFinishedReceiver();
我的问题是,我如何确保在任何时候都只注册了一个接收方
我希望用户能够在倒计时
正在运行时启动活动,但只有一个onReceive
运行。为什么CountDownTimer不在服务中?@sector11我认为独立于任何活动运行的最佳方式是在应用程序类中。你能详细谈谈你将如何做吗?