One of my apps does something very similar. To wake the service after a given period I recommend postDelayed()
Have a handler field:
private final Handler handler = new Handler();
and a refresher Runnable
private final Runnable refresher = new Runnable() {
public void run() {
// some action
}
};
You can fire your Notifications in the runnable.
On service construction, and after each execution start it like so:
handler.postDelayed(refresher, /* some delay in ms*/);
In onDestroy()
remove the post
handler.removeCallbacks(refresher);
To start the service at boot time you need an auto starter. This goes in your manifest
<receiver android:name="com.example.ServiceAutoStarter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
and the ServiceAutoStarter
looks like this:
public class ServiceAutoStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, UpdateService.class));
}
}
Stopping the OS from killing the service is tricky. Also your application can have a RuntimeException
and crash, or your logic can stall.
In my case it seemed to help to always refresh the service on screen on with a BroadcastReceiver
. So if the chain of updates gets stalled it will be resurrected as the user uses their phone.
In the service:
private BroadcastReceiver screenOnReceiver;
In your service onCreate()
screenOnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Some action
}
};
registerReceiver(screenOnReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
Then unregister your service on onDestroy()
with
unregisterReceiver(screenOnReceiver);