我正在使用MediPlayer来流式传输互联网广播,并在流式播放时在通知中心显示通知。
如果我离开应用程序(即通过home按钮),然后返回到应用程序的通知(广播播放在后台),我得到一个新的活动,我无法停止音乐,由于一个新的MediaPlayer实例被创建。
是否有任何方法可以停止所有MediaPlayer实例或返回到当前(活动)活动?
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
if (player.isPlaying()) {
buttonPlay.setEnabled(false);
buttonStopPlay.setEnabled(true);
}
super.onResume();
}
//Display notification in notification center
public void showStatus () {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("RADIO")
.setContentText("You're listening to RADIO");
Intent resultIntent= new Intent(this, MainActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(123, mBuilder.build());
}
您在哪里创建MediaPlayer
的实例?
如果你在Activity
内这样做,那么考虑改变你的策略。
正确的做法是:
- 创建一个
Service
,负责实例化和调用MediaPlayer
上的方法。 - 根据你的应用逻辑(即当一个按钮被点击时),
Activity
应该发布一个Intent
,指示Service
在MediaPlayer
上做一些操作。 - 当你出去并再次回到应用程序的"活动",无论是一个新的实例或一个旧的-将发布
Intents
的Service
的相同实例,从而到MediaPlayer
的相同实例。
要了解更多细节,您应该查看谷歌关于使用MediaPlayer的服务的文档