Running in the background

Some links

http://developer.android.com/training/best-background.html
http://www.quora.com/What-is-the-difference-between-services-and-intent-services-in-android
http://stackoverflow.com/questions/15524280/service-vs-intent-service
http://stackoverflow.com/questions/7771323/what-is-the-difference-between-an-intent-service-and-a-service

General

Unless you specify otherwise, most of the operations you do in an app run in the foreground on a special thread called the UI thread. This can cause problems, because long-running operations will interfere with the responsiveness of your user interface. This annoys your users, and can even cause system errors.

Services, Threads, IntentServices and AsyncTasks

http://www.onsandroid.com/2011/12/difference-between-android.html

Repeating tasks

TimerTask

- No changes in AndroidManifest needed.
- Stops when the application is stopped.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checker);
        Timer timer = new Timer();
        timer.schedule(timerTask, 3000, 3000);
    }

    public TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            Log.d("timer", "fire");
        }
    };

AlarmManager

https://developer.android.com/training/scheduling/alarms.html
http://vikinghammer.com/2012/04/22/android-use-alarmmanager-instead-of-a-service-with-a-timertask/
https://dhimitraq.wordpress.com/2012/11/27/using-intentservice-with-alarmmanager-to-schedule-alarms/

Start the alarm service:

MainAlarmService.Initialize(this);

The alarm service:

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainAlarmService extends IntentService {
    public MainAlarmService() {
        super("MainAlarmService");
    }

    public static void Initialize(Context context) {
        Intent alarmIntent = new Intent(context, MainAlarmService.class);
        PendingIntent pending = PendingIntent.getService(context, 0, alarmIntent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
                AlarmManager.INTERVAL_FIFTEEN_MINUTES,
                AlarmManager.INTERVAL_FIFTEEN_MINUTES,
                pending);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        NotificationHelper.showNotification(this, 1, "Alarm notification", "Alarm on " + date);  // For the NotificationHelper: see Android - Development
    }
}

Manifest:

<service
    android:name=".ServiceContainer$ScheduledService"
    android:exported="false"/>

Remark:
Start an exact alarm (needs more resources):

Intent myIntent = new Intent(context, MyServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,  0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 60); // first time
long frequency= 86400000 * 1000; // every 24 hours
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, pendingIntent);

http://stackoverflow.com/questions/22394615/intentservice-wont-start-using-alarmmanager

Boot receiver

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BootReceiver extends BroadcastReceiver {
    public BootReceiver() { super(); }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            NotificationHelper.showNotification(context, 2, "Boot notification", "Booted on " + date);
        }
    }
}

Manifest:

<receiver android:name=".BootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License