I want to run a service in the background as long as the android device is on. I already have a broadcastreceiver listening for BOOT_COMPLETED
to ensure it starts when it should, and it does. But when the main activity starts, I want to ensure that the service is still running and restart it if it's not. I'm fairly new to services to begin with so I'm not sure I'm doing it right.
In the manifest the service is defined as
<service
android:name="MyService"
android:icon="@drawable/myicon"
android:label="MyServiceLabel"
android:process=":my_process">
</service>
It's being started from the BroadcastReceiver using
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, OgLogService.class);
context.startService(service);
}
The meat of my service is
public int onStartCommand(Intent intent, int flags, int startId) {
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
// call web service, do stuff
}
}, 0, 1000 * 60);
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
Will this service stay on indefinitely or could the OS close it? If it's closed, how can my activity tell? If my activity does need to restart the service, do I need to do it in a special way to ensure that it's a separate process that won't die when the main activity dies? Sorry about having so many questions, I just feel a little misguided about services in their own processes (and services in general). Everything I read is about Services not in their own process.
I ask because at one point I believe I had the service running multiple times. The service and the activity don't interact directly. The service writes to the same DB that the activity reads from. At one point it appeared that information was duplicated in the database which I believe was caused by more than one instance of the service running at the same time.
I've tried using code from this answer but it doesn't seem to work for services running in different processes. In System Settings > Apps > Running, it shows my app running 1 process and 1 service (started by the broadcastreceiver) but the isMyServiceRunning
method returns false and stepping through it seems to not list my service.