0

I want to let my application check for data so that I am able to send notifications based on that data. Something like snapchat or facebook. When people send you snaps from snapchat you get a notification even though the app is not running or closed on the background. I want replicate a similar thing where I check for data in my FirebaseDatabase and display a notification based on that data. I've checked with BackgroundService but I'm not sure if it works in my case. So my question is what can I use to let my application check for updates (when connected to wifi) even though the app is not running?

Kristofer
  • 809
  • 9
  • 24

1 Answers1

1

You can do it using Service. Create a Service to put a listener with firebase and create a service to show your notifications. I have in my own app a ActivationService.class with this:

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    databaseReference = databaseReference.child("objects");
    valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                for (DataSnapshot objects : dataSnapshot.getChildren()) {
                    Object object = objects.getValue(Object.class);
                    if(object.getSomething.equals("1")){ //STATUS OR VALUE CHANGED THAT IS IMPORTANT
                        Intent intentNotification = new (ActivationService.this, NotificationService.class);
                        //put some extra if you like
                        startService(intentNotification);
                    }
                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    };
    databaseReference.addValueEventListener(valueEventListener);
    return super.onStartCommand(intent, flags, startId);
}

So in your NotificationService.class put something like:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //get your extras if you like to

    Notification notification = new NotificationCompat.Builder(context)
            .setTicker(ticker)
            .setContentTitle(title)
            .setContentText(desc)
            .setContentIntent(pendingIntentMain)
            .setSmallIcon(R.drawable.myIcon)
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setDefaults(Notification.DEFAULT_ALL)
            .addAction(action_ok)
            .addAction(action_off)
            .setOngoing(true)
            .build();

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, notification);

    return START_NOT_STICKY;
}

Just do not forget to remove your listener when the service get destroyed

@Override
public void onDestroy() {
    super.onDestroy();
    if (databaseReference != null && valueEventListener != null) {
        databaseReference.removeEventListener(valueEventListener);
    }
}

Popular applications do it using only one running service like MessageService from WhatsApp.

Gaspar
  • 1,515
  • 13
  • 20
  • Just a question when does this service get activated? – Kristofer May 18 '18 at 00:34
  • Your choice, making a *BOOT_COMPLETE BroadcastReceiver* to autorun when device boots [tutorial here](http://www.learn-android-easily.com/2013/07/bootcompleted-broadcastreceiver-in.html) or starting it from `MainActivity` with `Intent` – Gaspar May 18 '18 at 00:42
  • So Instead of using BOOT_COMPLETE I use and it doesnt seem to run my service when I try to log it – Kristofer May 18 '18 at 02:12
  • 1
    put `` to your ` – Gaspar May 18 '18 at 18:17
  • Just wondering but why would you need a service to start another service just for notifications? – Kristofer May 19 '18 at 21:35
  • You do not need to, but in my case i need it, because i start another services when needed by user status. You can use a method inside your class in one service only if you like to – Gaspar May 20 '18 at 00:45
  • Hey just another question but when I try to send a notification when the date of the item is todays date it doesn't send the notification. I did this if (dateFormat.getTime() == tomorrow.getTime()) – Kristofer May 24 '18 at 01:29
  • The notification is sent by the `PendingIntent`, if you need to make a notification in another time use the `AlarmManager` and set it to the `PendingIntent` of the notification – Gaspar May 24 '18 at 18:14