I'm using gcm
for chat, and I have an onMessageReceived()
method that receives the messages, saves them in the database, and sends a notification to the user.
When the app is running (or paused - running in the background), this is how I store the messages in the database:
private DBHelper mDbHelper;
mDbHelper = new DBHelper(MainApplication.getAppContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
The method getAppContext()
is a static method in my main activity which returns the context.
This all works. I receive a message, save it successfully, and get a notification (when app is running, or in the background).
Problem is when the app is closed. I can't use MainApplication.getAppContext();
, because there's no context when the app is closed.
Maybe I should pass the context in some other way?
UPDATE
Eventually I saved messages on server if the app was closed, and when user opens it I fetch'em from server, delete them from there, and save them on user's device. (like a queue pop
operation...)
Let me know if there's a better method
see accepted answer...