BroadCast接收器执行多次

时间:2016-02-12 15:02:12

标签: android android-broadcastreceiver

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

我的应用在CountDownTimer对象中有一个Application。它在这个类中的原因是因为一旦它被启动,用户应该能够在倒计时时移动到其他活动。

CountDownTimer倒计时后,我会启动LocalBroadcast,其中Activity已注册接收。

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

活动的launchMode设置为SingleInstancenoHistory设置为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

0 个答案:

没有答案