3

我在android中创建了一个mediplayer,它有一个可运行的后台线程来保持时间搜索器的更新

private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        long totalDuration = mediaPlayer.getDuration();
        long currentDuration = mediaPlayer.getCurrentPosition();

        // .... setting textviews of durations
           // ... converting milli to mm:ss and setProgress(progress)

        mHandler.postDelayed(this, 100);
    }
};

而且我在主要活动中有一个选项菜单,点击应该退出活动

public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.exitplayer)
            exitPlayer();
        return super.onOptionsItemSelected(item);
    }
    private void exitPlayer() {
        mediaPlayer.stop();
        mediaPlayer.release();
        try {
            mUpdateTimeTask.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    this.finish();

    }

但它抛出

java.lang.IllegalStateException 在 android.media.MediaPlayer.getDuration(本机方法)

我知道线程存在问题,应该在退出活动之前停止该线程,但我不知道究竟谁能帮助 plz?

4

1 回答 1

5

使用以下

mhandler.removeCallbacks(mUpdateTimeTask);

http://developer.android.com/reference/android/os/Handler.html

public final void removeCallbacks (Runnable r)

Added in API level 1
Remove any pending posts of Runnable r that are in the message queue.
于 2013-11-08T17:46:33.807 回答