gpt4 book ai didi

安卓媒体播放器 : how to stop a thread before finishing activity

转载 作者:太空宇宙 更新时间:2023-11-03 12:56:14 24 4
gpt4 key购买 nike

我在 android 中创建了一个 mediplayer,它有一个可运行的后台线程,用于保持时间搜索器的更新

private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mediaPlayer.getDuration();
long currentDuration = mediaPlayer.getCurrentPosition();

// .... setting textviews of durations
// ... converting milli to mm:ss and setProgress(progress)

mHandler.postDelayed(this, 100);
}
};

而且我在主 Activity 中有一个选项菜单,点击后应该退出 Activity

public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.exitplayer)
exitPlayer();
return super.onOptionsItemSelected(item);
}
private void exitPlayer() {
mediaPlayer.stop();
mediaPlayer.release();
try {
mUpdateTimeTask.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.finish();

}

但是它抛出

java.lang.IllegalStateException at android.media.MediaPlayer.getDuration(Native Method)

我知道线程存在问题,应该在退出 Activity 之前停止该线程,但我不知 Prop 体如何有人可以帮忙吗?

最佳答案

使用下面的

mhandler.removeCallbacks(mUpdateTimeTask);

http://developer.android.com/reference/android/os/Handler.html

public final void removeCallbacks (Runnable r)

Added in API level 1
Remove any pending posts of Runnable r that are in the message queue.

关于安卓媒体播放器 : how to stop a thread before finishing activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19865044/

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