Search code examples
javaandroidmedia-playerandroid-mediaplayer

Reusing Android Media Player effectively


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

Solution

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