3

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 ?

6
  • try mhandler.removeCallbacks(mUpdateTimeTask) Nov 8, 2013 at 17:35
  • did you try the above? Nov 8, 2013 at 17:43
  • wow , Thanks , actually I tried it before but this time worked :D Nov 8, 2013 at 17:45
  • what you mean by i you tried it before and not worked. Check my post and the link for the docs Nov 8, 2013 at 17:47
  • before sending the question I tried this line but with removeCallbacksAndMessages(mUpdateTimeTask) that time caused another exception , but now it works and exits activity without ptoblem . thanks Nov 8, 2013 at 17:50

1 Answer 1

5

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.
1
  • thanks it worked , sorry for my low reputations I cant vote up your answer Nov 8, 2013 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.