-1

I am trying to implement a background service that makes an HTTP request to an API every 15mins for the whole day, starting when a certain activity is started. I need the service to be started every 15 minutes even if my application is not running or I am in another activity of that application. I've searched for an example for how to proceed an have looked at some Stackoverflow questions and answers for example: Start Android Service after every 5 minutes. which linked to this page : http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/

From the discussion I know that I need to use an alarm manager, however all the implementations do not have this being done in the same activity they have broadcast receiver. The reason I would want to have the implementation in the same activity is because the results of the request is what I want to display on the UI.

Is there a way of implementing an alarm manager in this type of situation

Community
  • 1
  • 1
Tungamirai
  • 81
  • 11

1 Answers1

1

however all the implementations do not have this being done in the same activity they have broadcast receiver

That is because that is your only viable option, and even that will not work well on Android 6.0+. The recipe for using AlarmManager for this sort of scenario is to have it start a WakefulBroadcastReceiver, which in turn will work with an IntentService to do the work and go away when the work is completed.

On Android 6.0+, courtesy of "Doze mode", your AlarmManager events will not fire every 15 minutes, if the device is not charging and not moving. Also, courtesy of "app standby" on Android 6.0+, your AlarmManager events will not fire every 15 minutes, if the user has not been in your application's UI for some time and the device is not charging.

The reason I would want to have the implementation in the same activity is because the results of the request is what I want to display on the UI.

This runs counter to an earlier statement that you made:

I need the service to be started every 15 minutes even if my application is not running

If your application is not running, then you do not have an activity.

You are welcome to have your IntentService post a message on an event bus, such as greenrobot's EventBus, to let your activity know about the results of the work... if the activity happens to be around (otherwise, the message will be ignored).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491