Почему дополнительные данные об ответе OneSignal равны нулю?Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Почему дополнительные данные об ответе OneSignal равны нулю?

Сообщение Anonymous »

Наше мобильное приложение написано с использованием ReactNative. Нам нужно иметь возможность обрабатывать ответ на push-уведомление, даже если приложение свернуто или работает в фоновом режиме, поэтому необходим собственный код.
Вот код Android:

Код: Выделить всё

import android.util.Log;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;

import com.onesignal.notifications.IDisplayableMutableNotification;
import com.onesignal.notifications.INotificationReceivedEvent;
import com.onesignal.notifications.INotificationServiceExtension;

import org.json.JSONObject;

@Keep
public class OSNotificationService implements INotificationServiceExtension{

@Override
public void onNotificationReceived(@NonNull INotificationReceivedEvent event) {
IDisplayableMutableNotification notif = event.getNotification();
System.out.println("OSNotificationService raw payload: "+notif.getRawPayload());
if (notif.getAdditionalData() != null) {
System.out.println("OSNotificationService additional data: "+notif.getAdditionalData().toString());
JSONObject jsObj = notif.getAdditionalData();
}
else {
System.out.println("OSNotificationService additional data: null");
}
event.getNotification().display();
}
}
При запуске приложения на эмуляторе Android и получении уведомления OneSignal я увидел это в logcat (это правильно):

Код: Выделить всё

OSNotification raw payload: {
"google.delivered_priority": "high",
"google.sent_time": 9999999999,
"google.ttl": 9999999999,
"google.original_priority": "high",
"custom": "{\"i\":\"xxxxxxxxxx\",\"u\":\"xxxxxxxxxx:\/\/transaction\/xxxxxxxxxx\"}",
"google.product_id": 9999999999,
"pri": "10",
"from": "xxxxxxxxxx",
"alert": "Your invoice has been paid by the customer. Tap here to view the details.",
"title": "Invoice Paid",
"google.message_id": "xxxxxxxxxx",
"google.c.sender.id": "xxxxxxxxxx"
}
Проблема в этой строке:

Код: Выделить всё

System.out.println("OSNotificationService additional data: null");
Почему объект дополнительных данных имеет значение NULL? Я не работаю на внутренней стороне, и насколько я понимаю, объект data уже отправлен. Вот код (Go):

Код: Выделить всё

type NotificationPayload struct {
AppID            string                 `json:"app_id"`
Contents         map[string]string      `json:"contents"`
Headings         map[string]string      `json:"headings"`
Priority         int                    `json:"priority"`
URL              string                 `json:"url"`
TTL              int                    `json:"ttl"`
IncludeAliases   map[string][]string    `json:"include_aliases"`
TargetChannel    string                 `json:"target_channel"`
IosSound         string                 `json:"ios_sound,omitempty"`
AndroidChannelID string                 `json:"android_channel_id,omitempty"`
Data             map[string]interface{} `json:"data"`
}

func (c Client) SendNotification(
ctx context.Context,
externalID string,
contents Contents,
headings Headings,
url URL,
iosSound *string,
androidChannelID *string,
additionalData map[string]interface{},
) error {
client := httpclient.NewClient(30*time.Second, 3, 2*time.Second)
headers := map[string]string{
"Authorization": c.config.ApiKey,
"accept":        "application/json",
"content-type":  "application/json",
}

data := NotificationPayload{
AppID: c.config.AppId,
Contents: map[string]string{
"id": contents.ID,
"en": contents.EN,
},
Headings: map[string]string{
"id": headings.ID,
"en": headings.EN,
},
Priority: 10,
URL:      url.Value,
TTL:      259200,
IncludeAliases: map[string][]string{
"external_id": {externalID},
},
TargetChannel: "push",
Data:          additionalData,
}

// Only set optional fields if they are provided
if iosSound != nil {
data.IosSound = *iosSound
}
if androidChannelID != nil {
data.AndroidChannelID = *androidChannelID
}

body, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("failed to marshal data: %v", err)
}

resp, err := client.Do(
ctx,
"POST",
fmt.Sprintf("%s/%s", c.config.BaseEndpoint, "notifications?c=push"),
headers,
body,
)
if err != nil {
return fmt.Errorf("failed to send request: %v", err)
}
defer resp.Body.Close()

if resp.StatusCode != 200 {
return fmt.Errorf("failed to send email: %v", resp.Status)
}

return nil
}
Я использую React-native-onesignal 5.2.8, кстати.

Подробнее здесь: https://stackoverflow.com/questions/797 ... se-is-null
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»