Continually Running Background Service

I’m targeting sdk version 27 with a minimum version of 19 and trying to get a service that runs continuously in the background. I tried different service start options but it still got killed with the app. I tried using a BroadcastReceiver to start the service when it got killed but that gave me an error saying that the app was in the background and couldn’t start a service so I tried using the JobScheduler and that gave me the same error. How is this supposed to be done? For example, if I were making a pedometer app, how could I keep that running in the background?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

In oreo release Android defined limits to background services.

To improve the user experience, Android 8.0 (API level 26) imposes
limitations on what apps can do while running in the background.

Still if app need to run its service always, then we can create foreground service.

Background Service Limitations: While an app is idle, there are limits
to its use of background services. This does not apply to foreground
services, which are more noticeable to the user.

So create a foreground service. In which you will put a notification for user while your service is running. See this answer (There are many others)

Now what if you don’t want a notification for your service. A solution is for that.

You can create some periodic task that will start your service, service will do its work and stops itself. By this your app will not be considered battery draining.

You can create periodic task with Alarm Manager, Job Scheduler, Evernote-Jobs or Work Manager.

  • Instead of telling pros & cons of each one. I just tell you best. Work manager is best solution for periodic tasks. Which was introduced with Android Architecture Component.
  • Unlike Job-Scheduler(only >21 API) it will work for all versions.
  • Also it starts work after a Doze-Standby mode.
  • Make a Android Boot Receiver for scheduling service after device boot.

I created forever running service with Work-Manager, that is working perfectly.

Solution 2

Since Android 8.0 many background service limitations have been introduced.

Two solutions:

  1. if you need to get total control of task and execution timing, you have to choose Foreground Service.
    Pros: your app will be considered to be alive, then is more unlikely that the os will kill it to free resources.
    Cons: your user will always see the Foreground Notification.

  2. if you need to schedule periodically task, then Work Manager (introduced in Google I/O 18) is the best solution. This component choose the best possible scheduler (Jobscheduler, JobDispatcher, AlarmManager..). Keep in mind that work manager APIs are useful only for the tasks that require guaranteed execution and they are deferrable.
    Ref: Android Dev Documentation

Solution 3

The only solution I would suggest is using Firebase Cloud Messages.
Or foreground services.

Solution 4

Using BroadcastReciever we can run backgrouund service continuously, but if it will get killed , destroy automatically re-instance the old service instance
When service stops forcefully it will call onDestroy() method, in this case use one receiver and send one broadcast when ever service destroy and restart service again. in thee following method is custom action of reciever class which extends BroadcastReciever

public void onDestroy() {
    try {
    } catch (Exception e) {
    Intent intent = new Intent("");
    intent.putExtra("valueone", "tostoreagain");

and in onReceive Method

public void onReceive(Context context, Intent intent) {
    Log.i("Service Stoped", "call service again");
    context.startService(new Intent(context, ServiceCheckWork.class));

In case device is restarted then we have onBootCompleted action for receiver to catch

When you are targeting SdkVersion “O”

In define getPendingIntent()

private PendingIntent getPendingIntent() {
  Intent intent = new Intent(this, YourBroadcastReceiver.class);
 return PendingIntent.getBroadcast(this, 0, intent, 

here we use PendingIntent with BroadcastReceiver and This BroadcastReceiver has already been defined in AndroidManifest.xml.
Now in class which contains an onReceive() method:

public void onReceive(Context context, Intent intent) {
if (intent != null) {
   final String action = intent.getAction();
   if (ACTION_PROCESS_UPDATES.equals(action)) {
       NotificationResult result = NotificationResult.extractResult(intent);
       if (result != null) {
           List<Notification> notifications = result.getNotification();
           NotificationResultHelper notificationResultHelper = new 
                   context, notifications);
           // Save the notification data to SharedPreferences.
           // Show notification with the notification data.

Solution 5

as you say:

I tried using a BroadcastReceiver to start the service when it got
killed but that gave me an error saying that the app was in the
background and couldn’t start a service

in Oreo when you are in background and you want to start a service that service must be a foreground service use this code:

} else {

if you use this code in Oreo you have a few seconds in onStartCommand to start foreground otherwise your service considered as not responding and may be force close by user (in Android 8 or above)

There is no need to use BroadcastReceiver to start service after it is closed it is enough to just return START_STICKY or START_REDELIVER_INTENT from onStartCommand of your service to restart service after it is closed

Solution 6

A working hack for this is to simply start a foreground service which is only visible for the fraction of a second and starts your background service. In the background service you’d then periodically start the foreground service.
Before I give an example you should really ask yourself if this is the way to go for you, there might be other solutions to given problems (like using JobIntentService etc.); and keep in mind that this is a hack, it might be patched some time around and I’d generally not use it (I tested it with screen off and battery saving enabled though and it stayed alive the whole time – but this might prevent your device from dozing.. again, this is a dirty hack!)


public class TemporaryForegroundService extends Service {
public static final int NOTIFICATION_ID = 666;
private static Notification notification;

public void onCreate() {
    if(notification == null)
        notification = new NotificationCompat.Builder(this, NotificationChannels.importantChannel(this)).
                setSmallIcon(R.mipmap.ic_launcher).setContentTitle("The unseen blade").setContentText("If you see me, congrats to you.").build();
    startForeground(NOTIFICATION_ID, notification);
    startService(new Intent(this, PermanentBackgroundService.class));

public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;

public IBinder onBind(Intent intent) {
    return null;

public class PermanentBackgroundService extends Service {
    private Runnable keepAliveRunnable = new Runnable() {
        public void run() {
            if(handler != null) handler.postDelayed(this, 15*1000);
    private Handler handler;

    public void onCreate(){
        handler = new Handler();
        handler.postDelayed(keepAliveRunnable, 30* 1000);

    public void onDestroy() {

    private void keepServiceAlive() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(PermanentBackgroundService.this, TemporaryForegroundService .class));
        } else {
            startService(new Intent(PermanentBackgroundService.this, TemporaryForegroundService .class));

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply