#android #firebase #sqlite #firebase-cloud-messaging
#Android #firebase #sqlite #firebase-облако-обмен сообщениями
Вопрос:
Я хочу знать, как сохранить информацию, полученную из полезной нагрузки данных firebase cloud messaging. На самом деле я хочу, чтобы я получал поля с именем notification_type и другие данные из полезной нагрузки data, и я хочу сохранить их где-нибудь, когда приложение работает в фоновом режиме, и извлекать их, когда я когда-либо открываю свое приложение и обновляю свой пользовательский интерфейс на основе этого.
До сих пор я пытался сохранить его в Sharedprefrences, во внешнем файле и, наконец, в локальной базе данных, все это работало нормально и сохраняло данные, когда приложение было на переднем плане, но они не работали, когда приложение было в фоновом режиме.
Ниже приведен код, который я недавно попробовал для сохранения данных в локальной базе данных, он отлично работает, когда приложение находится на переднем плане, но не работает, когда приложение находится в фоновом режиме.
FireBaseMsgService.class
public class FireBaseMsgService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// for normal notifications
super.onMessageReceived(remoteMessage);
if(remoteMessage.getData().get("Notification_type").equals("2")){
String Org_Id=remoteMessage.getData().get("Org_Id");
String Unit_Id=remoteMessage.getData().get("Unit_Id");
String User_Id=remoteMessage.getData().get("User_Id");
String PatientId=remoteMessage.getData().get("PatientId");
String Notification_type=remoteMessage.getData().get("Notification_type");
if (remoteMessage.getNotification() != null){
String Click_Action=remoteMessage.getNotification().getClickAction();
User_Id=remoteMessage.getNotification().getTag();
saveNotificationDataToDb(getApplicationContext(),Notification_type);
FirebaseNotificationService firebaseNotificationService=new FirebaseNotificationService(
getApplicationContext(),
remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(),
Click_Action,
User_Id,
Org_Id,
Unit_Id,
PatientId,
Notification_type);
firebaseNotificationService.createNotification(remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(),
User_Id);
BusProvider.postOnMain(BusProvider.getInstance(),new NotifyingEvent(Notification_type));
//sendNotificationToFilesystem(Notification_type);
}
}
//for normal notifications
else{
if (remoteMessage.getNotification() != null){
String User_Id=remoteMessage.getNotification().getTag();
FirebaseNotificationService firebaseNotificationService=new FirebaseNotificationService(
getApplicationContext(),
remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(),
User_Id);
firebaseNotificationService.createNotification(remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(),
User_Id);
}
}
}
private void saveNotificationDataToDb(Context context , String notification_type) {
RecievedNotificationDbtable recievedNotificationDbtable=new RecievedNotificationDbtable(context);
recievedNotificationDbtable.open();
recievedNotificationDbtable.insertEntry(notification_type);
recievedNotificationDbtable.close();
}
}
Комментарии:
1. remoteMessage.getNotification() будет иметь значение null, если приложение работает в фоновом режиме. Переместите свой код для сохранения данных выше условия if (remoteMessage.getNotification()!=null)
Ответ №1:
Я ошибался в основах firebase docs, так как в документах четко сказано, что если есть полезная нагрузка уведомления, то это уведомление будет обрабатываться firebase sdk, а не методом onMessageReceived, поэтому я изменил отправку как полезной нагрузки данных, так и полезной нагрузки уведомления на просто полезную нагрузку данных, и после этого, когда я получаю уведомление о полезной нагрузке данных, вызывается onMessageReceived, и я могу вставить полезную нагрузку данных в свою локальную базу данных. итак, я изменил свой код на что-то вроде этого
FirebaseMsgService.class
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(remoteMessage.getData().get("Notification_type").equals("2")){
String Org_Id=remoteMessage.getData().get("Org_Id");
String Unit_Id=remoteMessage.getData().get("Unit_Id");
String User_Id=remoteMessage.getData().get("User_Id");
String PatientId=remoteMessage.getData().get("PatientId");
String Notification_type=remoteMessage.getData().get("Notification_type");
String Click_Action=remoteMessage.getData().get("click_action");
String title=remoteMessage.getData().get("title");
String body=remoteMessage.getData().get("body");
FirebaseNotificationService firebaseNotificationService=new FirebaseNotificationService(
getApplicationContext(),
title,
body,
Click_Action,
User_Id,
Org_Id,
Unit_Id,
PatientId,
Notification_type);
firebaseNotificationService.createNotification(title,
body,
User_Id);
saveNotificationDataToDb(getApplicationContext(),Notification_type);
BusProvider.postOnMain(BusProvider.getInstance(),new NotifyingEvent(Notification_type));
}
}
и сохраняются в БД с использованием этого метода
private void saveNotificationDataToDb(Context context , String notification_type) {
RecievedNotificationDbtable recievedNotificationDbtable=new RecievedNotificationDbtable(context);
recievedNotificationDbtable.open();
recievedNotificationDbtable.insertEntry(notification_type);
recievedNotificationDbtable.close();
}