如何阻止在UIThread上运行的Runnable

时间:2017-04-21 17:30:57

标签: java android multithreading

Runnable UIThread SeekBar更新MediaPlayerRunnable正在播放。然而,当我切换到另一个活动时,我的应用程序因异常而崩溃,导致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); } }); } } 在MediaPlayer被销毁后仍然永远保持。

这是我的代码:

ABCD.(123).(456)
789.(DEF) JKL.MNO
(PQ).(RS).(TUV)||(WXYz)

2 个答案:

答案 0 :(得分:2)

您需要使用:

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

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

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

答案 1 :(得分:0)

使用handler.removeCallbacks

从onStop中删除处理程序中的所有回调