0

I would like to implement a background service and a broadcast receiver to check if there's internet on my device and make http requests even when the app is closed, all of that from my activity. To do that, I checked the topics on this website but I don't understand some stuff. I don't understand how to do that, is OnReceive() function in my broadcast receiver called every time connectivity changes ? Or just when I register my receiver in my activity ? Can someone tell me more about what I need to do to achieve what I want ? I already created my broadcast receiver but I'm kind of lost for the other parts. Thanks

Messerschmitt
  • 267
  • 1
  • 3
  • 8
  • Possible duplicate of [Broadcast Receiver within a Service](http://stackoverflow.com/questions/9092134/broadcast-receiver-within-a-service) – rkmax Mar 18 '17 at 12:56

1 Answers1

0

First to create a Background Service within the scope of application you can use Handler classes,had it been outside the scope of app GCMTaskManger or JobScheduler could be used .

make http requests even when the app is closed, all of that from my activity

To do this use a JobScheduler or GCMTaskManager, that will call your http requests even when the app is closed.

Can someone tell me more about what I need to do to achieve what I want ?

So lets say you are using GCMTaskManager you will initialise the service first

 mGcmNetworkManager = GcmNetworkManager.getInstance(this);

then schedule your tasks to run within an interval

 PeriodicTask task = new PeriodicTask.Builder()
            .setService(MyTaskService.class)
            .setTag(TASK_TAG_WIFI)
            .setPeriod(30L)
            .build();

    mGcmNetworkManager.schedule(task);

and then listen for the events

 mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(MyTaskService.ACTION_DONE)) {
                String tag = intent.getStringExtra(MyTaskService.EXTRA_TAG);
                int result = intent.getIntExtra(MyTaskService.EXTRA_RESULT, -1);

                String msg = String.format("DONE: %s (%d)", tag, result);
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        }
    };

is OnReceive() function in my broadcast receiver called every time connectivity changes

That depends on the service whether it's generating events for the listener to listen,if yes then onReceive gets called.

I suggest you to read through this article for Schedulers https://www.bignerdranch.com/blog/choosing-the-right-background-scheduler-in-android/ Hope it helps.

OutOfBounds 94
  • 77
  • 1
  • 13