I have implelemented the START_STICKY command but the service is killed after a few hours. What I want to do is keep a service running always in the background and restart even when the device is rebooted. Can I restart the service in the onDestroy method like this? or is there a more convenient approach to it?
@Override
public void onDestroy() {
Stop();
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Intent i= new Intent(getApplicationContext(), MyService.class);
startService(i);
}
For ensuring that your service is running even after some hours of starting it, then you will have to use AlarmManager which will run recurringly for a specified periodicity even if the app is killed. What will you do is register a PendingIntent for the AlarmManager to fire which will be received by a BroadcastReceiver and in the BroadcastReceiver you will check that if your Service is running or not. If running, do nothing and if not then start the service.
What I want to do is keep a service running always in the background and restart even when the device is rebooted.
In order to do this you will have to give this permission in the manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
and then you will have to make a custom BroadcastReceiver which will check for an intent to be fired which is Action.BOOT_COMPLETED.
You should declare your BroadcastReceiver to catch the above mentioned intent in the Android Manifest like this:
<receiver android:name="com.example.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Now either you can initialise your AlarmManager in BroadcastReceiver class or you can write the code to start the service straightaway.
Info on AlarmManager can be found here.
Disclaimer: Starting from Android O, Google will stop supporting Unbound Background Service and calling startService() will become Illegal(Android will throw IllegalStateException) when calling this function.