Skip to content Skip to sidebar Skip to footer

Music Played Using Asynctask Isn't Stopping By Using Cancel

I am using a music in background of my activity. But when i am trying to cancel it its not working. The music is just continuously running until it finishes itself. Below is the c

Solution 1:

Instead of creating an AsyncTask, why not just create the MediaPlayer, and start it from your activity?

The MediaPlayer has its own threading logic built into it. You don't need to create a thread to manage the media player. You can read more here: http://developer.android.com/guide/topics/media/mediaplayer.html

In your activity, you could do the following:

privateMediaPlayer mMediaPlayer;

protectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Initalize the media player
    mMediaPlayer = ... however you are initializing it ...;

    // Set the listener so the media player can tell you when it is finished preparing
    mMediaPlayer.setOnPreparedListener(this);

    // Prepare the MediaPlayer asynchronously so that the UI thread does not lock up
    mMediaPlayer.prepareAsync();
}

// You need to listen for when the Media Player is finished preparing and is readypublicvoidonPrepared(MediaPlayer player) {
    // Start the player
    player.start();
}

Then whenever you need to stop the player, simply call

mMediaPlayer.stop();

Solution 2:

As, vogella explains it on his website: "The AsyncTask does not handle configuration changes automatically, i.e. if the activity is recreated, the programmer has to handle that in his coding.

A common solution to this is to declare the AsyncTask in a retained headless fragment."

Look for full text to: http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html#androidbackground

Post a Comment for "Music Played Using Asynctask Isn't Stopping By Using Cancel"