Android - 在服务中保留数据

时间:2018-01-27 09:56:31

标签: android service push-notification

我正在使用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;
    }
}

2 个答案:

答案 0 :(得分:0)

onMessageReceived将在后台线程上调用,因此您不应在此处使用AsyncTask。只需同步直接在这个方法中做你的东西。

答案 1 :(得分:0)

问题在于,当使用FireBase时,有两种类型的推送通知。

  1. 有效负载&#34;通知&#34;注册服务不会处理接收推送通知。
  2. Payload with&#34; data&#34;内容,将由注册服务处理。
  3. 来自Firebase文档(https://firebase.google.com/docs/cloud-messaging/android/receive):

    为大多数消息类型提供了

    onMessageReceived,但以下情况除外:

    • 当您的应用在后台时发送的通知消息。在这种情况下,通知将传递到设备的系统托盘。用户点按通知会默认打开应用启动器。

    • 包含通知和数据有效负载的消息,包括后台和前台。在这种情况下,通知将传递到设备的系统托盘,并且数据有效负载将在启动器活动的附加内容中传递。