gpt4 book ai didi

java - 如何停止在 UIThread 上运行的 Runnable

转载 作者:行者123 更新时间:2023-11-29 19:15:49 25 4
gpt4 key购买 nike

MediaPlayer 正在播放时,我在 UIThread 上有一个 Runnable 更新 SeekBar。然而,当我切换到另一个 Activity 时,我的应用程序因异常而崩溃,导致 Runnable 即使在 MediaPlayer 被销毁后也会永远保持运行。

这是我的代码:

public class Guide extends AppCompatActivity implements MediaPlayer.OnPreparedListener {

Button back;
private MediaPlayer m_audio_player;
private Handler m_handler_seek_bar = new Handler();
private SeekBar m_seek_bar;
private Runnable m_seek_bar_runnable;

private void set_up_audio(){
m_audio_player = MediaPlayer.create(this, g_audio[NativeLib.get_active_landmark()] );
m_audio_player.setOnPreparedListener(this);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guide);
implement_back_button();
set_up_audio();
}

@Override
protected void onStart() {
super.onStart();
set_up_seek_bar();
}

private void set_up_seek_bar() {
m_seek_bar = (SeekBar) findViewById(R.id.seek_bar);
m_seek_bar.setMax(m_audio_player.getDuration());
m_seek_bar_runnable = new Runnable() {
@Override
public void run() {
if(m_audio_player != null ){
m_seek_bar.setProgress(m_audio_player.getCurrentPosition());
}
m_handler_seek_bar.postDelayed(this, 1000);
}
};
// update Seekbar on UI thread
Guide.this.runOnUiThread(m_seek_bar_runnable);
m_seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(m_audio_player != null && fromUser){
m_audio_player.seekTo(progress);
}
}
});
}

@Override
protected void onStop() {
if (debug_mode) Log.d(TAG, "onStop");
if (m_audio_player.isPlaying()) {
m_audio_player.stop();
}
m_audio_player.release();
super.onStop();
findViewById(R.id.activity_guide).removeCallbacks(m_seek_bar_runnable);
}

// return button
private void implement_back_button() {
final Intent intent = new Intent(/* pointing at some other activity */);
back = (Button) findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(intent);
}
});
}
}

最佳答案

你需要使用:

m_handler_seek_bar.removeCallbacks(m_seek_bar_runnable);

handler 中移除 runnable

@Override
protected void onStop() {
if (debug_mode) Log.d(TAG, "onStop");
if (m_audio_player.isPlaying()) {
m_audio_player.stop();
}
m_audio_player.release();
m_handler_seek_bar.removeCallbacks(m_seek_bar_runnable);
super.onStop();
}

或者,您可以覆盖 Activity 的 onPause() 方法:

 @Override
protected void onPause() {
m_handler_seek_bar.removeCallbacks(m_seek_bar_runnable);
super.onPause();
}

关于java - 如何停止在 UIThread 上运行的 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43548767/

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