Android前台通知启动新活动(通过挂起意图),而不是现有的活动

6

我有一个音乐流应用程序,当音乐正在流式传输时,我想显示前台通知。我在单独的服务中进行流媒体传输,以下是我用于前台通知的代码:

Notification notification = new Notification(R.drawable.ic_stat_notification, getString(R.string.app_name), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, PlayerActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this,getString(R.string.app_name),
                   getString(R.string.streaming), pendingIntent);
startForeground(4711, notification);

这个符号显示在任务栏中,如果我点击通知,应用程序会打开,但它是一个全新的活动(我猜是因为创建了一个新的Intent)。所以,如果我在应用程序中打开对话框,当我关闭应用程序(点击主屏幕)并在通知栏中滑动/点击应用程序图标时,对话框就不再打开。如何处理这种情况,以便显示“旧/真实”的活动?

2个回答

16

你需要使用标志(flags)来完成这个任务。你可以在此处阅读有关标志的相关资料:http://developer.android.com/reference/android/content/Intent.html

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

来自上面的链接:

如果设置了此标志,如果活动已经运行在历史记录堆栈的顶部,则不会启动该活动。

单一任务栈模式将启动一个新的活动,如果当前没有正在运行的实例,如果已有一个实例正在运行,则意图将被发送到 onNewIntent()


1
很遗憾,你没有提到android:launchMode="singleTop",这是用户https://dev59.com/VGHVa4cB1Zd3GeqPl1hW#13876977的建议。 - user25

7

//在您的Activity中

Notification notification = new Notification(R.drawable.ic_stat_notification, getString(R.string.app_name), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, PlayerActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this,getString(R.string.app_name),
                   getString(R.string.streaming), pendingIntent);
startForeground(4711, notification);

//在你的清单文件中

android:name="com.package.player.MusicPlayerActivity"

android:launchMode="singleTop"

完美的解决方案,谢谢。 - Vishva Vijay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接