我实现了一个扩展 CountDownTimer 的类,它能正常工作,但当屏幕关闭时,定时器就会失去同步。因此,当我离开活动或屏幕关闭时,CountDownTimer 应该继续正确地工作。我拥有
<uses-permission android:name="android.permission.WAKE_LOCK"/>
权限,并尝试使用 PowerManager
,但我认为问题不在那里。请帮我解决这个问题。PowerManager pm = (PowerManager) getSystemService((MenuApp.this).POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
myTimer = new CustomTimer(min, 1000);
myTimer.start();
wl.release();
.
@TargetApi(Build.VERSION_CODES.GINGERBREAD) @SuppressLint("NewApi")
public class CustomTimer extends CountDownTimer
{
public CustomTimer(long millisInFuture, long countDownInterval)
{
super( millisInFuture, countDownInterval );
byteTimer = 1;
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
@Override
public synchronized void onTick(long millisUntilDone)
{
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilDone)- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilDone)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilDone)-TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilDone)));
tim.setText(hms);
edit.putLong("Minute", millisUntilDone-1669);
edit.commit();
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
@Override
public synchronized void onFinish()
{
tim.setText("00:00");
seconds = 0L;
if(btnToggle.isChecked()){
btnToggle.setChecked(false);
btnToggleTimer.setChecked(false);
}else{
btnToggle.setChecked(true);
btnToggleTimer.setChecked(false);
}
}
}
CustomTimer
实例并调用start()
方法。然后设备可以回到睡眠状态。 - CommonsWare