我想要有一个定时器对话框,它将从0开始,每5秒发出一个声音。它适用于Nexus S API 22的仿真器,但不适用于我的HTC One M8 API 21手机。记录日志消息并在模拟器上听到声音,但在我的实际电话上都没有发生,所以我认为这不是一个合理的问题。为什么if语句在仿真器上工作,但不在实际设备上工作
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime/1000);
int mins = secs/60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
if(secs > 0 && ((secs%5) == 0) && milliseconds == 0){
Log.d("BEEP", "beep");
tg.startTone(ToneGenerator.TONE_PROP_BEEP);
}
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
这里也是用于参考的onCreate和变量名。
public class TimerDialogFragment extends DialogFragment implements DialogInterface.OnClickListener{
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
ToneGenerator tg;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreateDialog(savedInstanceState);
View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_timer,null);
tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
timerValue = (TextView) v.findViewById(R.id.timerText);
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
return new AlertDialog.Builder(getActivity())
.setView(v)
.setMessage("")
.setCancelable(true)
.setNegativeButton("Continue with instructions",this)
.create();
}
....
}
为什么postDelayed()为0的值?这根本不符合逻辑。 – BladeCoder
我想实际更新时钟,以显示时间进度。 –
您应该使用非零延迟来避免CPU烧毁。每100ms更新计时器显示应该足够了。 – BladeCoder