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());
}
}
}
答案 0 :(得分:0)
我使用邮递员发送数据通知(用于测试)。在接收数据消息时,执行onMessageReceived()方法。 现在,即使应用程序处于后台,我也可以在数据库中保存通知。