1

I am trying to read from my Firebase database even when my application is closed. How do I create a thread or background task which runs even when the app is closed. I need it to be connected to the internet.

I also tried to use Firebase Cloud Messaging to recieve notifications but I cannot send any message from phone X to phone Y.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • See https://stackoverflow.com/questions/42210186/handling-keepsynced-while-on-background-on-android-and-with-fcm/42210878#42210878 and more from this list https://stackoverflow.com/search?q=%5Bfirebase%5D%5Bandroid%5D+background – Frank van Puffelen Aug 12 '17 at 15:20

3 Answers3

2

You will want to create a Service that runs even when your application is closed.

Consult https://developer.android.com/guide/components/services.html or any of the fine Service tutorials.

J_H
  • 17,926
  • 4
  • 24
  • 44
1

If you want to check something periodically then use WakefulBroadcastReceiver. You can start a service from onReceive and perform the task you want. Stop the service as soon as the task is finished. This is more efficient and will save battery too as compare to running a service all the time.

public class MyReceiver extends WakefulBroadcastReceiver {

    private AlarmManager alarmMgr;
    private PendingIntent alarmIntent;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (!isServiceRunning(UpdateAppService.class, context)) {

            Intent service = new Intent(context, MyService.class);
            service.putExtra("source", "Reciever");
            startWakefulService(context, service);

        }
    }

    public void setAlarm(Context context, long syncTime) {
        alarmMgr = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(context, MyReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                syncTime, syncTime, alarmIntent);

    }

    public void cancelAlarm(Context context) {
        if (alarmMgr != null) {
            alarmMgr.cancel(alarmIntent);
        }
    }

    public static boolean isServiceRunning(Class<?> serviceClass, Context context){
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        try {
            for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (serviceClass.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        return false;
    }
}
Harsh
  • 599
  • 3
  • 20
0

What you need is Firebase Job Dispatcher.

Running a Service for this is not a good idea because the operative system can kill to prioritize the app in the foreground. A Service is an excellent idea to create scalable apps that need background work while they are active, a music player or some REST app, by example.

Using an alarm, the AlarmManager is battery expensive and doesn't allow you to set constraints to what you want, what if you want to run your job only when the device is on Wi-Fi. Also, alarms are lost in device boot.

For doing something like catching network connection developers used to rely on BroadcastReceivers, but network connectivity is not available anymore since API 25 due the abused of it. That is why Android provide JobScheduler, the problem with it is that a JobScheduler is not retro-compatible and is only available API 23 and above. A costly solution is to use JobScheduler and AlarmManager.

Firebase Job Dispacther is much like a cron job with conditions, it will only execute when the conditions are met, can handle the boot, can be executed one or recursively, is battery efficient, and the window of time, while is executed, is well handled. This used to be GcmNetworkManager, is now updated.

Evernote did a similar library Android Job but I rather rely on the great people on Firebase and Google.

cutiko
  • 9,887
  • 3
  • 45
  • 59