In Android you can set AlarmManger
to wakes up every X milliseconds and run a PendingIntent
.
This code looks something like this.
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()+60000,
PERIOD,
pi);
Android's default IntentService
that runs in the background has some limitations.
You can also take a look at external libary WakefulIntentService
(https://github.com/commonsguy/cwac-wakeful). I use that along with AlarmManager
to run background tasks.
Updated:
OnAlarmReceiver class
public class OnAlarmReceiver extends BroadcastReceiver {
public static String TAG = "OnAlarmReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Waking up alarm");
WakefulIntentService.sendWakefulWork(context, YourService.class); // do work in the service class
}
}
YourService class
public class YourService extends WakefulIntentService {
public static String TAG = "YourService";
public YourService() {
super("YourService");
}
@Override
protected void doWakefulWork(Intent intent) {
Log.d(TAG, "Waking up service");
// do your background task here
}
}