我如何在android中停止runnable线程?

时间:2014-04-25 08:36:55

标签: android multithreading

我正在使用postDelayed线程,我需要在按下后退按钮时停止该线程。任何人都可以帮助我。提前完成。

这是我的主题:

music1.postDelayed(new Runnable() {
    public void run() {
          music1.setVisibility(View.VISIBLE);
        animationmusic1();
        holemusic1();

    }
}, 10000);

3 个答案:

答案 0 :(得分:7)

http://developer.android.com/reference/android/view/View.html#removeCallbacks(java.lang.Runnable)

Runnable runnable声明为实例变量。然后

runnable =new Runnable() {
    public void run() {
         music1.setVisibility(View.VISIBLE);
         animationmusic1();
         holemusic1();
    }
    };
music1.postDelayed(runnable,10000);

然后在onPause

music1.removeCallbacks(runnable);

答案 1 :(得分:2)

在YourActivity中添加onBackPressed()

/** (non-Javadoc)
     * @see android.app.Activity#onBackPressed()
     */    
@Override
    public void onBackPressed() {
        music1.removeCallbacks(runnable);
        YourActivity.super.onBackPressed();
    }

答案 2 :(得分:0)

handler.removeCallbacks(runnable);