我做了一个计时器,如果按秒,100毫秒为单位计时,则时间显示的很流畅。
如果改为10毫秒为单位,在模拟器上显示也很流畅,但安装到手机里后反应就缓慢了,有延迟,时间每次不是0.01秒的显示,而是中间有很大间隔
如果改为1毫秒为单位,在模拟器上显示都不流畅了,在手机上更不行了。
该怎么解决呢?
我的实现方法为:
1.设置计时器,时间间隔mlTimerUnit根据用户的设置设置不同的值
按秒计时,则为1000
按100毫秒计时,则为100
按10毫秒计时,则为10
按1毫秒计时,则为1 if (null == timer) {
if (null == task) {
task = new TimerTask() {

@Override
public void run() {
// TODO Auto-generated method stub
if (null == msg) {
msg = new Message();
} else {
msg = Message.obtain();
}
msg.what = 1;
handler.sendMessage(msg);
}

};
}

timer = new Timer(true);
timer.schedule(task, mlTimerUnit, mlTimerUnit); // set timer duration
}2.显示计时时间的方法
        // Handle timer message
        handler = new Handler(){
     @Override
     public void handleMessage(Message msg) {
     // TODO Auto-generated method stub
     switch(msg.what) {
     case 1:
     mlCount++;
     int totalSec = 0;
     int yushu = 0;
    
     if (SETTING_SECOND_ID == settingTimerUnitFlg) {
// second
     totalSec = (int)(mlCount);
} else if (SETTING_100MILLISECOND_ID == settingTimerUnitFlg) {
// 100 millisecond
totalSec = (int)(mlCount / 10);
         yushu = (int)(mlCount % 10);
} else if (SETTING_10MILLISECOND_ID == settingTimerUnitFlg) {
// 10 millisecond
totalSec = (int)(mlCount / 100);
         yushu = (int)(mlCount % 100);
} else if (SETTING_MILLISECOND_ID == settingTimerUnitFlg) {
// 1 millisecond
totalSec = (int)(mlCount / 1000);
         yushu = (int)(mlCount % 1000);
}
    
     // Set time display
     int min = (int)(totalSec / 60);
     int sec = (int)(totalSec % 60);
     try{
     if (SETTING_SECOND_ID == settingTimerUnitFlg) {
     // second(1000ms)
     tvTime.setText(String.format("%1$02d:%2$02d", min, sec));
     } else if (SETTING_100MILLISECOND_ID == settingTimerUnitFlg) {
     // 100 millisecond
     tvTime.setText(String.format("%1$02d:%2$02d:%3$d", min, sec, yushu));
     } else if (SETTING_10MILLISECOND_ID == settingTimerUnitFlg) {
     // 10 millisecond
     tvTime.setText(String.format("%1$02d:%2$02d:%3$02d", min, sec, yushu));
     } else if (SETTING_MILLISECOND_ID == settingTimerUnitFlg) {
     // 1 millisecond
     tvTime.setText(String.format("%1$02d:%2$02d:%3$03d", min, sec, yushu));
     }
     } catch(Exception e) {
     tvTime.setText("" + min + ":" + sec + ":" + yushu);
     e.printStackTrace();
     Log.e("MyTimer onCreate", "Format string error.");
     }
     break;
    
     default:
     break;
     }
    
     super.handleMessage(msg);
     }
    
     };