我想知道如何更好地使用Android中的MediaPlayer对象,以便如果我进入应用程序中的其他活动,那么当前的声音播放就不会停止。例如,我目前在一堂课中使用了MediaPlayer,在该课程中进行了AlarmManager接收(BroadcastreCeiver)。这是我拥有的,有更好的方法可以做到吗?
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();
}
}
}
您可以使用服务。请参阅以下链接。http://www.java2s.com/code/android/media/usingservicetoplaymediafile.htm