如何在Android中每秒更改一次TextView

her*_*erp 16 android

我制作了一个简单的Android音乐播放器.我希望有一个TextView,以分钟为单位显示歌曲中的当前时间:秒格式.所以我尝试的第一件事就是让活动Runnable并把它放在run()中:

int position = 0;
while (MPService.getMP() != null && position<MPService.duration) {
try {
    Thread.sleep(1000);
    position = MPService.getSongPosition();
} catch (InterruptedException e) {
    return;
}

// ... convert position to formatted minutes:seconds string ...

currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);
Run Code Online (Sandbox Code Playgroud)

但这失败了因为我只能在创建它的线程中触摸TextView.所以我尝试使用runOnUiThread(),但是这不起作用,因为在主线程上重复调用Thread.sleep(1000),因此活动只挂在空白屏幕上.那么我有什么想法可以解决这个问题?


新代码:

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)); // no problem here
        if (seconds < 10) {
            // this is hit, yet the text never changes from the original value of 0:00
            currentTime.setText(String.format("%d:0%d",minutes,seconds));
        } else {
            currentTime.setText(String.format("%d:%d",minutes,seconds));
        }
        timeHandler.postAtTime(this,(((minutes*60)+seconds+1)*1000));
    }

};

private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
        IBinder rawBinder) {
      appService = ((MPService.LocalBinder)rawBinder).getService();

    // start playing the song, etc. 

    if (startTime == 0) {
        startTime = appService.getSongPosition();
        timeHandler.removeCallbacks(updateTime);
        timeHandler.postDelayed(updateTime,1000);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*jti 12

那这个呢:

    int delay = 5000; // delay for 5 sec.
    int period = 1000; // repeat every sec.

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask()
        {
            public void run()
            {
                //your code
            }
        }, delay, period);
Run Code Online (Sandbox Code Playgroud)


Mus*_*sis 10

使用a Timer(而不是while带有a 的循环Thread.Sleep).有关如何使用计时器定期更新UI元素的示例,请参阅此文章:

从计时器更新UI

编辑:更新后退链接,感谢Arialdo:http://web.archive.org/web/20100126090836/http : //developer.android.com/intl/zh-TW/resources/articles/timed-ui-updates html的

编辑2:非回程链接,感谢gatoatigrado:http://android-developers.blogspot.com/2007/11/stitch-in-time.html