我想要有一個定時器對話框,它將從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