我正在使用 MediPlayer 流式传输网络广播,并在播放流式传输时在通知中心显示通知。
如果我离开应用程序(即通过主页按钮),然后返回应用程序并收到通知( radio 在后台播放),我会得到一个新的 Activity ,由于新的实例,我无法停止音乐正在创建 MediaPlayer。
有什么方法可以停止所有 MediaPlayer 实例或返回当前( Activity ) Activity 吗?
@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
上进行一些操作。 - 当您出去并再次回到应用程序时,无论是新实例还是旧实例,“Activity”都会将
Intents
发布到Service
的同一实例> 并因此到MediaPlayer
的同一实例。
有关更多详细信息,您应该查看 Google 关于 Using a Service with MediaPlayer 的文档.
关于java - MediaPlayer 并通过 Intent 返回当前 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22503287/