意图恢复先前暂停的活动(从通知调用)
我正在开发一个向用户显示通知的应用程序。通知的目的是让用户在其他活动中时能够轻松返回到该活动。我在我的应用程序中使用此代码来创建和显示通知。
notification = new Notification(R.drawable.icon,
"Notify",
System.currentTimeMillis());
notification.setLatestEventInfo(this, "App name",
"App message",
PendingIntent.getActivity(
this, 0,
new Intent(this, Main.class),
PendingIntent.FLAG_CANCEL_CURRENT));
notification.flags |= Notification.FLAG_ONGOING_EVENT;
nManager.notify(0, notification);
但是,当用户点击通知时,会启动同一活动的新实例,而不是用户之前使用的实例。
我认为这与 PendingIntent 有关,但我找不到如何使该 Intent 恢复先前暂停的活动实例而不是创建新实例。
谢谢。
I'm developing an app which shows a notification to the user. The notification's objective is to make it easy to the user to return to the activity when the user is in another activity. I am using this code in my app to create and show the notification.
notification = new Notification(R.drawable.icon,
"Notify",
System.currentTimeMillis());
notification.setLatestEventInfo(this, "App name",
"App message",
PendingIntent.getActivity(
this, 0,
new Intent(this, Main.class),
PendingIntent.FLAG_CANCEL_CURRENT));
notification.flags |= Notification.FLAG_ONGOING_EVENT;
nManager.notify(0, notification);
But when the user taps the notification starts a new instance of the same activity, instead of the one that the user was using before.
I think this has something to do with PendingIntent but I can't find how to make that Intent to resume a previously paused instance of the activity instead of creating a new instance.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我知道怎么做了。我添加了以下代码:
现在我的代码如下所示:
I found out how to do it. I added the following code:
Now my code looks like this:
这对我有帮助
android:launchMode="singleInstance"
This helps for me
android:launchMode="singleInstance"
我通过设置解决了同样的问题
I solved the same problem by setting
创建 PendingIntent 时,您可以使用:
如果您想返回同一个活动,您应该使用默认的活动上下文。在这里阅读更多内容:
Android - 什么是获取Context的各种方法之间的区别?
When creating your PendingIntent, you use:
You should use the default Activity context if you want to return to the same activity. Read more here:
Android - what's the difference between the various methods to get a Context?
除了@Jimix 的正确答案之外,我还将
PendingIntent
requestCode
从 0 更改为非零值,如另一个答案。另一方面,之前的版本存在已知错误 Android 版本花了我绝望的几个小时。那里提出的解决方案对我来说效果很好,在发送通知之前取消PendingIntent
:Apart from the correct answer of @Jimix I would change the
PendingIntent
requestCode
from 0 to a non zero value as commented on another answer. On the other hand, there is a known bug on previous Android versions that took me a couple of desperate hours. The solution proposed there worked fine for me cancelling thePendingIntent
before of sending the notification: