当应用程序处于后台时,无法成功保存FCM消息,因为它在应用程序处于前台时工作

时间:2017-09-16 10:31:45

标签: android database firebase-cloud-messaging

FCM服务。 NotificationDatabaseHandler是辅助类。保存邮件标题和当前时间。

public class ApplicationFCMService extends FirebaseMessagingService {

    private static final String TAG = ApplicationFCMService.class.getName();
    private NotificationUtils notificationUtils;
    private NotificationDatabaseHandler databaseHandler;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.e(TAG, "From: " + remoteMessage.getFrom());
        databaseHandler = new NotificationDatabaseHandler(getApplicationContext());

        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());

            databaseHandler.addNotification(remoteMessage.getNotification().getBody(), getDate());
            //  Log.d("FCM", messagesSet.toString());
            Log.d("FCM", remoteMessage.getNotification().getBody());
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我使用邮递员发送数据通知(用于测试)。在接收数据消息时,执行onMessageReceived()方法。 现在,即使应用程序处于后台,我也可以在数据库中保存通知。