-1

如果我启用每秒刷新线程,我制作了一个音乐播放器,每次尝试关闭它时都会崩溃(刷新是为了更新歌曲的经过时间和进度条)。这是代码:

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {
           long totalDuration = mp.getDuration();
           long currentDuration = mp.getCurrentPosition();

           // Displaying Total Duration time
           songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
           // Displaying time completed playing
           songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

           // Updating progress bar
           int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
           //Log.d("Progress", ""+progress);
           songProgressBar.setProgress(progress);

           // Running this thread after 100 milliseconds
           mHandler.postDelayed(this, 100); //this line is causing errors
       }
    };

这一切都在活动中再次起作用,但是一旦我按下后退按钮,它就会崩溃。有任何想法吗?谢谢

4

1 回答 1

1

Try stopping the future callbacks with removeCallbacks() in onPause() or a similar method:

mHandler.removeCallbacks(mUpdateTimeTask);

if I enable refreshing the thread every sec

You seem to want to run your code once a second, but you use...

// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100); //this line is causing errors

Understand that Handlers and Runnables are not created in a new Thread by default and that a 100 millisecond delay executes your code 10 times a second.

于 2012-12-28T21:38:48.853 回答