MediaPlayer并通过Intent返回到当前活动



我正在使用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内这样做,那么考虑改变你的策略。

正确的做法是:

  1. 创建一个Service,负责实例化和调用MediaPlayer上的方法。
  2. 根据你的应用逻辑(即当一个按钮被点击时),Activity应该发布一个Intent,指示ServiceMediaPlayer上做一些操作。
  3. 当你出去并再次回到应用程序的"活动",无论是一个新的实例或一个旧的-将发布IntentsService的相同实例,从而到MediaPlayer的相同实例。

要了解更多细节,您应该查看谷歌关于使用MediaPlayer的服务的文档

最新更新