gpt4 book ai didi

android - 如何在 Android 中每秒更改一个 TextView

转载 作者:可可西里 更新时间:2023-11-01 18:45:01 26 4
gpt4 key购买 nike

我制作了一个简单的 Android 音乐播放器。我想要一个 TextView 以分钟:秒格式显示歌曲中的当前时间。所以我尝试的第一件事是使 Activity 可运行并将其放入 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);

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


新代码:

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

最佳答案

这个怎么样:

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

关于android - 如何在 Android 中每秒更改一个 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5188295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com