0

I would like to know how to reuse the MediaPlayer object in Android better so that if I go into other activities within my app, the current sound playing won't stop. For example, I currently used MediaPlayer inside a class where I do AlarmManager receiving (BroadcastReceiver). Here is what I have, are there better ways to do this?

public class MyBroadcastReceiver extends BroadcastReceiver
{
   MediaPlayer mp;


@Override
public void onReceive(Context context, Intent intent)
{
    // TODO Auto-generated method stub
    mp = new MediaPlayer();
    playSound(context);
}
private void playSound(Context ctx)
{
    //play the notification sound
    AssetFileDescriptor afd = null;
    try
    {
        afd = ctx.getAssets().openFd("notify.mp3");
    } 
    catch (IOException e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    mp.setVolume(5f, 5f);
    try
    {
        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    } 
    catch (IllegalArgumentException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    catch (IllegalStateException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try
    {
        mp.prepare();
    } 
    catch (IllegalStateException | IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mp.start();
    if(!mp.isPlaying())
    {
        mp.release();
    }
}
}
Karim O.
  • 1,325
  • 6
  • 22
  • 36

1 Answers1

0

you can use service. Please refer the below link. http://www.java2s.com/Code/Android/Media/UsingServicetoplaymediafile.htm

Ranjith KP
  • 858
  • 6
  • 18