I need to keep my service always running in background. And starting my service with "startService()" function. I don't want to restart service whatever is Application's state.
Here is my observations.
START_STICKY > if application starts , service is restarting. And service is restarting itself when application closes , too.
START_NOT_STICK > service doesn't work after application closed.
I need a service which always running , and it will receive broadcast when application starts. Services status musn't depend if application is running or not.
Can you help me ?
Thanks.
you will want to set a BOOT receiver which starts your Service ALARM (which will wake up intermittently and make sure your Service is running) when the device boots. The ALARM receiver should wakes up every minute (or so) to see that your Service hasn't been cleaned up by Android (which will happen from time to time).
[EDIT]
You'll want a BootReceiver to start your alarm that will look like this:
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), 0);
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 2000, 60000, pendingIntent);
}
}
And an alarmReceiver would look like this:
public class AlarmReceiver extends BroadcastReceiver {
private String TAG = "AlarmReceiver";
// onReceive must be very quick and not block, so it just fires up a Service
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyLovelyService.class);
PendingIntent.getService(context, 0,i, 0).send();
}
}
and lastly this needs to go into your manifest:
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name=".AlarmReceiver" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With