Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Running a background task every 15 minutes, even when application is not running

I need to build a background task that runs every 10/15 minutes (doesn't really matter, either is good), even when the application is not running.

How can I accomplish this? I can't seem the wrap my head around this.

I read I could use some sort of runnable() functionality or use a background services or AlarmManager. I was thinking of a background service, since it also must be done when the application itself is not running.

What is a better way of doing this and how could I do it?

like image 465
DijkeMark Avatar asked Apr 22 '13 19:04

DijkeMark


People also ask

How do you handle long running background tasks?

You still should use foreground services to perform tasks that are long running and need to notify the user that they are ongoing. If you use foreground services directly, ensure you shut down the service correctly to preserve resource efficiency.

Which component is used to run long running background in Android?

Android provides platform support to execute with and without a user interface. An Android service is defined as an application component that is generally used to perform long tasks in the background without needing user input.

What is Android background task?

What is it? Background processing in Android refers to the execution of tasks in different threads than the Main Thread, also known as UI Thread, where views are inflated and where the user interacts with our app.


1 Answers

You have have detemined the amount of time (interval) to execute a snippet of code, its better to use AlarmManager because its more energy effient. If your app needs to listen to some sort of a event , then Service is what you need.

public static void registerAlarm(Context context) {
    Intent i = new Intent(context, YOURBROADCASTRECIEVER.class);

    PendingIntent sender = PendingIntent.getBroadcast(context,REQUEST_CODE, i, 0);

    // We want the alarm to go off 3 seconds from now.
    long firstTime = SystemClock.elapsedRealtime();
    firstTime += 3 * 1000;//start 3 seconds after first register.

    // Schedule the alarm!
    AlarmManager am = (AlarmManager) context
            .getSystemService(ALARM_SERVICE);
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
            600000, sender);//10min interval

}
like image 186
wtsang02 Avatar answered Sep 21 '22 17:09

wtsang02