I'm developing an android app that has a Room database and receives notifications with Firebase Cloud Messaging. What I'm trying to implement is a way for the notifications to be saved into the database so the user can see them at any time.
I have accomplished this for notifications that are received while the app is running in the foreground, but not when it's closed.
The code I have is as follows for the messaging service:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMessagingServ";
public static int NOTIFICATION_ID = 1;
/**
* Executed when a notification message is received
* @param remoteMessage
*/
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
generateNotification(remoteMessage.getNotification().getBody(),
remoteMessage.getNotification().getTitle());
MyNotificacion noti = new MyNotificacion();
noti.setTitulo(remoteMessage.getNotification().getTitle());
noti.setContenido(remoteMessage.getNotification().getBody());
//other data
//Creating the instance here didn't work either
//MyDatabase db = Room.databaseBuilder(getApplicationContext(),
// MyDataBase.class, DATABASE_NAME)
// .build();
MyDatabase db = MyApp.database;
if (db != null) new InsertNotiAsyncTask(db.getMyNotificacionDao()).execute(noti);
//all this does is invoking the insert method in the corresponding Dao
}
//other methods
}
This is my app class:
public class MyApp extends Application {
public static MyDatabase database;
@Override
public void onCreate() {
super.onCreate();
database = MyDatabase.getInstance(MyApp.this);
}
}
And this is the database class:
@Database(entities = {MyNotificacion.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
public static final String DATABASE_NAME = "my_db";
private static MyDatabase instance;
public static MyDatabase getInstance(final Context contexto){
if(instance == null){
instance = Room.databaseBuilder(
contexto.getApplicationContext(),
MyDatabase.class,
DATABASE_NAME
).build();
}
return instance;
}
public abstract MyNotificacionDao getMyNotificacionDao();
}
The main problem is that getting the database instance requires a context. I have followed this method as a workaround so I can do this operation from a class that's not an activity, but it simply doesn't work when a notification is received while the app is closed.
Is there any other way to achieve this?
So far I've thought I could maybe save the db instance with shared preferences, but I don't know if it would work, nor does it seem very logical to have persistence for the persistence. Would this be my only other option?