我有一个带圆形进度条的柜台。计数器启动时,进度条也从计数器值开始,但是当它在后台运行并再次打开应用程序时...圆形进度条从0开始,但计数器按值正确运行。在这种情况下,我需要进度条不要从0开始。
这是我的代码:
public class MainActivity extends AppCompatActivity {
public int counter;
Button button;
public boolean isrunningtime = false;
TextView textView;
private ProgressBar progressBar;
long millisUntilFinished = 0;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
sharedPreferences = getSharedPreferences("my", MODE_PRIVATE);
editor = sharedPreferences.edit();
progressBar = findViewById(R.id.progressBar);
startService(new Intent(this, BroadcastService.class));
Log.i("Tag", "Started service");
}
private BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent); // or whatever method used to update your GUI fields
}
};
@Override
public void onResume() {
super.onResume();
registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
Log.i("Tag", "Registered broacast receiver");
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(br);
}
@Override
public void onStop() {
try {
unregisterReceiver(br);
} catch (Exception e) {
// Receiver was probably already stopped in onPause()
}
super.onStop();
}
@Override
public void onDestroy() {
stopService(new Intent(this, BroadcastService.class));
Log.i("Tag", "Stopped service");
super.onDestroy();
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
millisUntilFinished = intent.getLongExtra("countdown", 0);
Log.i("Tag", "Countdown seconds remaining: " + millisUntilFinished / 1000);
progressBar.setProgress((int) (millisUntilFinished / 1000));
Log.i("progress", "" + (int) (millisUntilFinished / 1000));
textView.setText("" + millisUntilFinished / 1000);
}
}
}
答案 0 :(得分:0)
仅在unregisterReceiver(br)
中放入onDestroy()
,而不是onStop()
和onPause()
答案 1 :(得分:0)
从onStop()和onPause()中删除unregisterReceiver(br);
,并将registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
从onResume()移至onCreate()