gpt4 book ai didi

android - 单击通知不会打开 Android 应用程序

转载 作者:行者123 更新时间:2023-12-05 04:04:35 24 4
gpt4 key购买 nike

我正在使用 onesignal 和 firebase 将通知从 wordpress 博客推送到 Android 应用程序,当我点击刚刚到达的通知时,应用程序只有在后台运行时才会打开。如果它完全关闭,则单击通知将不会执行任何操作。应用未在后台打开,如何实现点击通知打开应用?

下面是处理通知的代码:

 class nyonNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
@Override
public void notificationOpened(OSNotificationOpenResult result) {

OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
String customKey;

if (data != null) {
customKey = data.optString("customkey", null);
if (customKey != null)
Log.i("OneSignalnyon", "customkey set with value: " + customKey);
}

if (actionType == OSNotificationAction.ActionType.ActionTaken)
Log.i("OneSignalnyon", "Button pressed with id: " + result.action.actionID);

// The following can be used to open an Activity of your choice.
// Replace - getApplicationContext() - with any Android Context.
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

最佳答案

我用来在点击通知时打开应用程序的代码,它工作得很好:

 Intent resultIntent = new Intent(getApplicationContext(), YourActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//if you want to send some data
resultIntent.putExtra(AppConstants.NOTIFICATION, data);

现在你必须创建 PendingIntentPendingIntent:根据文档,创建待定 Intent 意味着您授予它执行您指定的操作的权利,就好像另一个应用程序是您自己一样。 https://developer.android.com/reference/android/app/PendingIntent

PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT
);

现在,当您创建通知时,将此待定 Intent setContentIntent(resultPendingIntent) 设置为该通知。

  Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(System.currentTimeMillis() + ""))
.setSmallIcon(R.drawable.ic_app_icon)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), icon))
.setContentText(message)
.setChannelId(CHANNEL_ID)
.build();

关于android - 单击通知不会打开 Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com