0

我有一个问题,我BroadcastReceiver的注册数次。

我的应用程序中有一个CountDownTimer对象Application。之所以在这个类中,是因为一旦启动,用户应该能够在倒计时的同时移动到其他活动。

一旦CountDownTimer倒计时,我就会启动LocalBroadcast某个Activity注册接收的。

除了onReceive被称为多次之外,一切正常。例如,如果用户CountDownTimer在 Activity1 中启动,然后移动到 Activity2,然后返回到 Activity1,onReceive则调用两次。

launchModeActivity 的 设置为并SingleInstance设置noHistorytrue。这是我尝试只拥有一个注册 Activity 的实例,并希望拥有一个接收器。

这是我CountDownTimerApplication对象:

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时,我才调用以下内容:CountDownTimerApplication

initializeCountDownFinishedReceiver();
        registerCountDownFinishedReceiver();

.

我的问题是如何确保在任何时候都只有在 Receiver 上注册?

我希望用户能够在运行时多次启动 Activity,CountDownTimer但只onReceive运行一次。

4

0 回答 0