Search code examples
androidmultithreadingandroid-mediaplayer

Android MediaPlayer : how to stop a thread before finishing activity


I have created a mediplayer in android which has a runnable background thread for keeping the time seeker updated

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

and also I have a option menu in the main activity that on click should exit the activity

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

    }

but it throws

java.lang.IllegalStateException at android.media.MediaPlayer.getDuration(Native Method)

I know there is a problem in threading and should stop that thread before exiting activity but I don't know exactly how can anyone help plz ?


Solution

  • Use the below

    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.