我的MainActivity中有处理程序,起初它工作得很好,但是由于某种原因它突然不起作用,因此不再每秒都重复该方法。
private void showElapsedTime() {
SharedPreferences pref = getSharedPreferences("chronometer",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
long elapsedMillis = (SystemClock.elapsedRealtime() - chronometer.getBase())/1000;
editor.putLong("time",elapsedMillis);
Log.d(TAG, "seconds"+elapsedMillis);
editor.commit();
}
@Override
protected void onStart(){
super.onStart();
firebaseauth.addAuthStateListener(authListener);
mChildReference1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange (DataSnapshot dataSnapshot){
String status = dataSnapshot.getValue(String.class);
if (status.equals ("occupied")) {
chronometer.start();
handler1.postDelayed(new Runnable() {
@Override
public void run() {
showElapsedTime();
handler1.postDelayed(this, 1000); //every seconds
}
},0);
else
handler1.removeCallbacksAndMessages(null);
}
答案 0 :(得分:1)
尝试
private Handler handler = new Handler();
private Runnable runnable;
handler.postDelayed(runnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(runnable, 1000);
}
}, 1000);
您需要将相同的可运行对象传递给run函数中的第二个处理程序。