0

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 code:

public class xx extends Activity 
{ BackgroundSound mBackgroundSound = new BackgroundSound();

  @Override
protected void onCreate(Bundle savedInstanceState) 
{ ....
     }

  @Override
protected void onResume() 
{
    super.onResume();
    mBackgroundSound.execute();
}

@Override
protected  void onPause()
  {
      super.onPause();
      mBackgroundSound.cancel(true);
      }

and for options menu selection:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
         mBackgroundSound.cancel(true);
                NavUtils.navigateUpFromSameTask(this);

                return true;
    case R.id.menu_Add:
        { mBackgroundSound.cancel(true);
            Intent intent = new Intent(xx.this,yy.class);
                intent.putExtra("flag", "add");
                intent.putExtra("AddObj", "mm");

            startActivity(intent);
            break;
        }
    case R.id.menu_list_quote:
        {
            mBackgroundSound.cancel(true);
            Intent intent = new   Intent(xx.this,zz.class);
                intent.putExtra("Obj", "nn");

            startActivity(intent);

            break;
        }   


    }
    //return true;
    return super.onOptionsItemSelected(item);
}

and the asynTask:

 public class BackgroundSound extends AsyncTask<Void, Void, Void> {
     @Override
     protected Void doInBackground(Void... params) {
         try
         {
             while( !isCancelled())
             {

            // FileDescriptor afd = openFd("cock_alarm.mp3");
             MediaPlayer player = new MediaPlayer();
             player.setDataSource(_musicFilePath);
             player.prepare();
             //player.setLooping(true); // Set looping 
             player.setVolume(100,100); 
             player.start(); 
           //  if(isCancelled())
            //   player.stop();
             }

         }
         catch(Exception exp)
         {
             exp.printStackTrace();
         }
         return null;
      }
        }

Also, tried using for loop:

  for(int i=0;i<100 && !isCancelled();i++)

and tried this inside try block of asyncTask:

if(isCancelled())
 player.stop();

How am i going to solve it?

Shaon Hasan
  • 730
  • 7
  • 17
  • You should not use `AsyncTask` for this in the first place. It's not appropriate for anything more than [a few seconds](http://developer.android.com/reference/android/os/AsyncTask.html). – kabuko Mar 20 '14 at 18:28

2 Answers2

6

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:

private MediaPlayer mMediaPlayer;

protected void onCreate(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 ready
public void onPrepared(MediaPlayer player) {
    // Start the player
    player.start();
}

Then whenever you need to stop the player, simply call

mMediaPlayer.stop();
Jon Nale
  • 206
  • 1
  • 2
1

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

Mica Noise
  • 11
  • 1