私がBroadcastReceiver
何度も登録されるという問題があります。
私のアプリケーションにはCountDownTimer
、Application
オブジェクトが含まれています。このクラスに含まれている理由は、一度開始すると、カウントダウン中にユーザーが他のアクティビティに移動できる必要があるためです。
CountDownTimer
がカウントダウンしたら、LocalBroadcast
特定のActivity
が受信するように登録されている を起動します。
onReceive
複数回呼び出されることを除けば、すべて正常に機能します。たとえば、ユーザーが Activity1 で を開始しCountDownTimer
、Activity2 に移動してから Activity1 に戻った場合、onReceive
が 2 回呼び出されます。
launchMode
アクティビティの が に設定され、SingleInstance
がnoHistory
に設定されtrue
ます。これは、登録するアクティビティのインスタンスを 1 つだけ、できればレシーバーを 1 つだけ持つという私の試みです。
これは私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);
}
}
In onCreate
iでは、 がクラスCountDownTimer
で実行されている場合にのみ次を呼び出します。Application
initializeCountDownFinishedReceiver();
registerCountDownFinishedReceiver();
.
私の質問は、一度に登録された受信者だけが存在することを確認するにはどうすればよいですか?
実行中にユーザーがアクティビティを何度でも起動できるようにしたいのですが、CountDownTimer
実行は 1 回だけonReceive
です。