我再次向你求助于我提出的一个问题。 我有一个扩展类服务的类,并实现了Runnable类用于音频播放,我正在使用进度条来显示音乐再现的进度。在run方法中添加代码以更新进度条的值,就在那里,但是当我正在播放一首歌并跳转到另一首歌而没有完成前一个时,之前创建的线程不会被破坏,请帮助我请?
public class PlaySongService extends Service implements MediaPlayer.OnCompletionListener, Runnable {
public static MediaPlayer mediaPlayer = new MediaPlayer();
private ProgressBar pbSong;
private final String TAG = "PlaySongService";
@Override
public IBinder onBind(Intent intent) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void onCreate() {
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.reset();
pbSong = new WeakReference<ProgressBar>(Main.pbSong);
super.onCreate();
}
....... /* Selected song in listview*/
private void playSong(int position) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(my_file_selected_in_listview);
mediaPlayer.prepare();
mediaPlayer.start();
pbSong.get().setProgress(0);
pbSong.get().setMax(mediaPlayer.getDuration());
new Thread(this).start();
} catch (Exception e) {
Log.e(TAG,e.getMessage());
}
}
@Override
public void run() {
int currentPosition= 0;
int total = mediaPlayer.getDuration();
while (mediaPlayer!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mediaPlayer.getCurrentPosition();
Log.i(TAG,Thread.currentThread().toString());
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
pbSong.get().setProgress(currentPosition);
}
}
}
答案 0 :(得分:0)
在正常情况下,线程不会被“破坏”,它们在运行方法return
时结束。这可以通过例如布尔标志或通过调用interrupt()
(线程外部)并定期检查线程中的Thread.interrupted()
。