Cannot insert a record into SQLite database from Firebase messaging service when application is in background or closed

I am trying to notify Firebase. I was able to properly configure the notification using this documentation. A message was received, and I was able to send a notification to the notification panel from the service class MyFirebaseMessagingService. This happens even when the application is in the background or closed.

I need to collect the data sent in the notification and paste it into the SQLite database. The code I wrote works fine if the application is in the foreground, but it does not work if it is closed or in the background. Here is what I wrote for the insert.

DbHelper dbh=new DbHelper(this,"sample.sqlite",null,1);
SQLiteDatabase sdb=dbh.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("id","1");
cv.put("name","testname");
sdb.insert("test",null,cv);
sdb.close();
dbh.close();

Appreciate any help with this. Thanks in advance.

<service android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

<service android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>

public class MyFirebaseMessagingService extends FirebaseMessagingService
{
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        Log.i("Tag","inside message" );
        Log.i(StaticInfo.INFO, "From: " + remoteMessage.getFrom());
        Log.i(StaticInfo.INFO, "Notification Message Title  : " + remoteMessage.getNotification().getTitle());
        Log.i(StaticInfo.INFO, "Notification Message Body   : " + remoteMessage.getNotification().getBody());

        insertPromotion();
        sendNotification(remoteMessage.getNotification().getBody());
    }

    private void sendNotification(String messageBody) 
    {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase Push Notification")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }

    private void insertPromotion() 
    {
        DbHelper dbh = new DbHelper(this, "sample.sqlite", null, 1);
        SQLiteDatabase sdb = dbh.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put("id","1");
        cv.put("name","testname");
        sdb.insert("test", null, cv);
        sdb.close();
        dbh.close();

        Log.i("Tag","db closed");
    }

}
+2
2

onMessageReceived , . , .

Firebase :

- FCM . .

. . -.

, , . Firebase Console. , . JSON, notification.

{
   "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
   "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   },
}
+4

, onMessgeReceived(), SQLite, ( ), :

1) , IntentService, :

public class SQLService extends IntentService {
    private final static String MESSAGE_ID = "message_id";

    private MySQLiteDbAdapter mySQLiteAdapter;

    public SQLService() {
        super("test-service");
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // initialize SQLite adapter here using getApplicationContext()
        this.mySQLiteAdapter = new MySQLiteDbAdapter(getApplicationContext());

    }

    @Override
    protected void onHandleIntent(Intent intent) {

        // fetch data to save from intent
        Message message = new Message();
        Message.setMessage_id(intent.getStringExtra(MESSAGE_ID));
        ...
        // save 
        this.mySQLiteAdapter.add(message);

    }
}

2) onMessageReceived() Firebase, :

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        if (remoteMessage.getData() != null) {

            Intent intent = new Intent(this, SQLService.class);
            // add data to intent
            intent.putExtra(MESSAGE_ID, remoteMessage.getData().get(MESSAGE_ID));
            ...
            // start the service
            startService(intent);

        }
    }

3) AndroidManifest.xml:

<application
  ...
        <service
            android:name=".SQLService"
            android:exported="false"/>
  ...

. https://guides.codepath.com/android/Starting-Background-Services

0

Source: https://habr.com/ru/post/1655824/


All Articles