Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Periodic Background Service - Advice

I am working on an app that will relay information about its location to a remote server. I am intending to do it by doing a simple HTTP post to the web-server and all is simple and fine.

But according to the spec, the app needs to execute itself from time to time, lets say once in every 30 mins. Be independent of the interface, meaning which it needs to run even if the app is closed.

I looked around and found out that Android Services is what needs to be used. What could I use to implement such a system. Will the service (or other mechanism) restart when the phone restarts?

Thanks in advance.

like image 856
Ziyan Junaideen Avatar asked May 02 '12 19:05

Ziyan Junaideen


People also ask

What is the current recommended way to handle long running background tasks in Android?

Recommended solutionScheduling deferred work through WorkManager is the best way to handle tasks that don't need to run immediately but which ought to remain scheduled when the app closes or the device restarts.

What is background services in Android?

A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.

Why did Android OS limit the power given to background services?

Background Service Limitations. Services running in the background can consume device resources, potentially resulting in a worse user experience.


1 Answers

Create a Service to send your information to your server. Presumably, you've got that under control.

Your Service should be started by an alarm triggered by the AlarmManager, where you can specify an interval. Unless you have to report your data exactly every 30 minutes, you probably want the inexact alarm so you can save some battery life.

Finally, you can register your app to get the bootup broadcast by setting up a BroadcastReceiver like so:

public class BootReceiver extends BroadcastReceiver {     @Override     public void onReceive(Context context, Intent intent) {           if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {             // Register your reporting alarms here.                     }     } } 

You'll need to add the following permission to your AndroidManifest.xml for that to work. Don't forget to register your alarms when you run the app normally, or they'll only be registered when the device boots up.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> 
like image 102
Argyle Avatar answered Oct 02 '22 17:10

Argyle