我有一个名为"OtpVerification"的活动,其中包含 30 秒的计时器,在此过程中,如果我退出应用程序然后重新打开应用程序,它会产生问题 1)几秒钟后,当我重新打开应用程序时,应用程序从 MainActivity 启动而不是该活动和 2) 应用程序崩溃。
这是场景:-场景:当自动 OTP 验证过程开始时启动 30 秒计时器,现在用户尝试通过按返回按钮结束此过程并退出应用程序,然后他立即在几秒钟内重新启动应用程序。现在,随着计时器过期并且应用程序尝试启动手动 OTP 验证屏幕,这将创建一个致命的异常,应用程序崩溃。
这是代码:-
@SuppressLint("SetTextI18n")
private void init() {// initialize view controls
//Initialize a new CountDownTimer instance
long m_MillisInFuture = 30000;// timer value
long m_CountDownInterval = 1000;// timer break up
m_oTimer = new CountDownTimer(m_MillisInFuture, m_CountDownInterval) {
public void onTick(long millisUntilFinished) {
@SuppressWarnings("UnusedAssignment") long millis = millisUntilFinished;
@SuppressLint("DefaultLocale") String hms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
System.out.println(hms);
tv.setText(hms);
//Another one second passed
//Each second ProgressBar progress counter added one
m_n_ProgressStatus += 1;
m_timerProgress.setProgress(m_n_ProgressStatus);
}
public void onFinish() {// when timer finished
/*This is new change ....check if app is in backround or foreground*/
/*if app is in background*/
if (NetworkUtil.isAppIsInBackground(getApplicationContext())) {
System.out.println("In Background");
/*if app is in background start service */
Intent startService = new Intent(getApplicationContext(), OTPIntentService.class); // if condition match then start service to notify server regarding app installation
getApplicationContext().startService(startService);// start service
} else {
System.out.println("In Foreground");
/*if app is in forground than send request to server*/
verifyOTP();
}
}
}.start();// start timer
// retreive progress bar count........
int progressBarMaximumValue = (int) (m_MillisInFuture / m_CountDownInterval);
//Set ProgressBar maximum value
//ProgressBar range (0 to maximum value)
m_timerProgress.setMax(progressBarMaximumValue);
//Display the CountDownTimer initial value
tv.setText(progressBarMaximumValue + "Seconds...");
}
@Override
public void onDestroy() {// unregister broadcast receiver ........
super.onDestroy();
getApplicationContext().unregisterReceiver(m_oOtpReceiver);// unregistaer broadcast receiver.
}
尝试在onPause()中取消注册您的接收器,并在onResume()中创建并将标志更改为false,然后在onResume()中检查标志是否为假,然后再次重新注册接收器。我的应用程序中遇到了类似的问题,这些确实帮助了我。
有点像我在应用程序中实现的,我从我的服务中调用了接收器
@Override
protected void onResume() {
super.onResume();
registerReceiver();
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
isReceiverRegistered = false;
super.onPause();
}
private void registerReceiver(){
if(!isReceiverRegistered) {
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(SessionStore.REGISTRATION_COMPLETE));
isReceiverRegistered = true;
}
}