为什么这个if语句适用于模拟器但不适用于实际设备

时间:2015-07-18 21:44:14

标签: android multithreading

我希望有一个定时器对话框,从0开始,每5秒发出一次声音。它在Nexus S API 22的仿真器上完美运行,但在我的HTC One M8 API 21手机上不起作用。记录日志消息并在模拟器上听到声音,但在我的实际手机上都没有,所以我认为这不是一个合理的问题。

 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();
}

....

}

1 个答案:

答案 0 :(得分:1)

在此片段中:

    if(secs > 0 && ((secs%5) == 0) && milliseconds == 0){
        Log.d("BEEP", "beep");
        tg.startTone(ToneGenerator.TONE_PROP_BEEP);
    }

你指望milliseconds为0才能发出哔哔声。这不是一个可靠的假设 - 这是一种非常糟糕的编码实践。如果您想每5秒发出一次哔声,请将Runnable更改为:

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, 5000);  // <<<<<<<<<
   }
};