我正在使用Firebase进行推送通知。问题是如果我的应用程序关闭且只有NotificationService在后台运行,则不会保存通知。
保存正在运行以防我的应用程序运行。
我应该如何在服务中保留数据?
NotificationReceiver extends FirebaseMessaginService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
saveNotification(buildNotificationObjet(remoteMessage));
if(getPreference("displayNotifications") != 0) {
sendNotification(remoteMessage.getNotification().getBody());
}
}
}
private void saveNotification(Notification notification) {
new PersistTask(getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE)).execute(notification);
}
保存在PersistTask中完成
private static class PersistTask extends AsyncTask<Notification, Void, List<Notification>> {
SharedPreferences preferences;
public PersistTask(SharedPreferences preferences) {
this.preferences = preferences;
}
@Override
protected List<Notification> doInBackground(Notification... paramNotification) {
Gson gson = new Gson();
Type type = new TypeToken<List<Notification>>(){}.getType();
List<Notification> notifications = gson.fromJson(preferences.getString(PREFERENCE_LIST_NAME, ""), type);
if(notifications == null) {
notifications = new ArrayList<>();
}
notifications.addAll(Arrays.asList(paramNotification));
SharedPreferences.Editor editor = preferences.edit();
editor.putString(PREFERENCE_LIST_NAME, gson.toJson(notifications));
editor.apply();
return notifications;
}
}
答案 0 :(得分:0)
onMessageReceived
将在后台线程上调用,因此您不应在此处使用AsyncTask
。只需同步直接在这个方法中做你的东西。
答案 1 :(得分:0)
问题在于,当使用FireBase时,有两种类型的推送通知。
来自Firebase文档(https://firebase.google.com/docs/cloud-messaging/android/receive):
为大多数消息类型提供了onMessageReceived,但以下情况除外:
当您的应用在后台时发送的通知消息。在这种情况下,通知将传递到设备的系统托盘。用户点按通知会默认打开应用启动器。
包含通知和数据有效负载的消息,包括后台和前台。在这种情况下,通知将传递到设备的系统托盘,并且数据有效负载将在启动器活动的附加内容中传递。