无法使用Handler每秒更新TextView

时间:2011-03-10 07:38:00

标签: android

我正在尝试每秒更新一次TextView。特别是它是一首歌的计时器。我正在使用Handler来实现这一点。它似乎设置正确 - 我没有任何异常,我调试时没有看到任何明显错误 - 但它悄然无法更新TextView。它只停留在0:00。

private TextView currentTime;
private int startTime = 0;
private Handler timeHandler = new Handler();
private Runnable updateTime = new Runnable() {
    public void run() {
        final int start = startTime;
        int millis = appService.getSongPosition() - start;
        int seconds = (int) ((millis / 1000) % 60);
        int minutes = (int) ((millis / 1000) / 60);
        Log.d("seconds",Integer.toString(seconds)); // looks okay, prints new value every second
        if (seconds < 10) {
            // this is hit, yet the textview is never updated
            currentTime.setText(String.format("%d:0%d",minutes,seconds));
        } else {
            currentTime.setText(String.format("%d:%d",minutes,seconds));
        }
        timeHandler.postAtTime(this,start+(((minutes*60)+seconds+1)*1000));
    }
};

private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
        IBinder rawBinder) {
    appService = ((MPService.LocalBinder)rawBinder).getService(); // service that handles the MediaPlayer

    // start playing the song, etc...

    if (startTime == 0) {
        startTime = appService.getSongPosition();
        timeHandler.removeCallbacks(updateTime);
        timeHandler.postDelayed(updateTime,1000);
    }
}

public void onServiceDisconnected(ComponentName classname) {
    appService = null;
}
};

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.song);

    currentTime = (TextView) findViewById(R.id.current_time);

    // ...

    bindIntent = new Intent(Song.this,MPService.class);
    bindService(bindIntent,onService,0);
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)