Android Service needs to run always (Never pause or stop)

JavaAndroidService

Java Problem Overview


I created a service and want to run this service always until my phone restarts or force closed. The service should run in background.

Sample code of created service and start services:

Start the service:

Intent service = new Intent(getApplicationContext(), MyService.class);
getApplicationContext().startService(service);

The service:

public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful
        HFLAG = true;
        //smsHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 1000);
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO for communication return IBinder implementation
        return null;
    }
}

Manifest declaration:

<service
    android:name=".MyService"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
</service>

Is it possible to run this service always as when the application pauses and anything else. After some time my application goes pause and the services also go pause or stop. So how can I run this service in background and always.

Java Solutions


Solution 1 - Java

"Is it possible to run this service always as when the application pause and anything else?"

Yes.

  1. In the service onStartCommand method return START_STICKY.

     public int onStartCommand(Intent intent, int flags, int startId) {
             return START_STICKY;
     }
    
  2. Start the service in the background using startService(MyService) so that it always stays active regardless of the number of bound clients.

     Intent intent = new Intent(this, PowerMeterService.class);
     startService(intent);
    
  3. Create the binder.

     public class MyBinder extends Binder {
             public MyService getService() {
                     return MyService.this;
             }
     }
    
  4. Define a service connection.

     private ServiceConnection m_serviceConnection = new ServiceConnection() {
             public void onServiceConnected(ComponentName className, IBinder service) {
                     m_service = ((MyService.MyBinder)service).getService();
             }
    
             public void onServiceDisconnected(ComponentName className) {
                     m_service = null;
             }
     };
    
  5. Bind to the service using bindService.

             Intent intent = new Intent(this, MyService.class);
             bindService(intent, m_serviceConnection, BIND_AUTO_CREATE);
    
  6. For your service you may want a notification to launch the appropriate activity once it has been closed.

     private void addNotification() {
             // create the notification
             Notification.Builder m_notificationBuilder = new Notification.Builder(this)
                     .setContentTitle(getText(R.string.service_name))
                     .setContentText(getResources().getText(R.string.service_status_monitor))
                     .setSmallIcon(R.drawable.notification_small_icon);
    
             // create the pending intent and add to the notification
             Intent intent = new Intent(this, MyService.class);
             PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
             m_notificationBuilder.setContentIntent(pendingIntent);
    
             // send the notification
             m_notificationManager.notify(NOTIFICATION_ID, m_notificationBuilder.build());
     }
    
  7. You need to modify the manifest to launch the activity in single top mode.

               android:launchMode="singleTop"
    
  8. Note that if the system needs the resources and your service is not very active it may be killed. If this is unacceptable bring the service to the foreground using startForeground.

             startForeground(NOTIFICATION_ID, m_notificationBuilder.build());
    

Solution 2 - Java

In order to start a service in its own process, you must specify the following in the xml declaration.

<service
  android:name="WordService"
  android:process=":my_process" 
  android:icon="@drawable/icon"
  android:label="@string/service_name"
  >
</service> 

Here you can find a good tutorial that was really useful to me

http://www.vogella.com/articles/AndroidServices/article.html

Hope this helps

Solution 3 - Java

A simple solution is to restart the service when the system stops it.

I found this very simple implementation of this method:

How to make android service unstoppable

Solution 4 - Java

If you already have a service and want it to work all the time, you need to add 2 things:

  1. in the service itself:

     public int onStartCommand(Intent intent, int flags, int startId) {
         return START_STICKY;
     }
    
  2. In the manifest:

     android:launchMode="singleTop"
    

No need to add bind unless you need it in the service.

Solution 5 - Java

You can implement startForeground for the service and even if it dies you can restart it by using START_STICKY on startCommand(). Not sure though this is the right implementation.

Solution 6 - Java

I found a simple and clear way of keeping the Service running always.

This guy has explained it so clearly and have used a good algorithm. His approach is to send a Broadcast when the service is about to get killed and then use it to restart the service.

You should check it out: http://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android

Solution 7 - Java

You don't require broadcast receiver. If one would take some pain copy one of the api(serviceconnection) from above example by Stephen Donecker and paste it in google you would get this, https://www.concretepage.com/android/android-local-bound-service-example-with-binder-and-serviceconnection

Solution 8 - Java

Add this in manifest.

      <service
        android:name=".YourServiceName"
        android:enabled="true"
        android:exported="false" />

Add a service class.

public class YourServiceName extends Service {


    @Override
    public void onCreate() {
        super.onCreate();

      // Timer task makes your service will repeat after every 20 Sec.
       TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                       // Add your code here.

                     }

               });
            }
        };
  //Starts after 20 sec and will repeat on every 20 sec of time interval.
        timer.schedule(doAsynchronousTask, 20000,20000);  // 20 sec timer 
                              (enter your own time)
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful
      
      return START_STICKY;
    }

}

Solution 9 - Java

I had overcome this issue, and my sample code is as follows.

Add the below line in your Main Activity, here BackGroundClass is the service class.You can create this class in New -> JavaClass (In this class, add the process (tasks) in which you needs to occur at background). For Convenience, first denote them with notification ringtone as background process.

 startService(new Intent(this, BackGroundClass .class));

In the BackGroundClass, just include my codings and you may see the result.

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class BackgroundService  extends Service {
    private MediaPlayer player;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
     player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI);
        player.setLooping(true);
         player.start();
        return START_STICKY;
    }
 @Override
    public void onDestroy() {
        super.onDestroy();
         player.stop();
    }
}

And in AndroidManifest.xml, try to add this.

<service android:name=".BackgroundService"/>

Run the program, just open the application, you may find the notification alert at the background. Even, you may exit the application but still you might have hear the ringtone alert unless and until if you switched off the application or Uninstall the application. This denotes that the notification alert is at the background process. Like this you may add some process for background.

Kind Attention: Please, Don't verify with TOAST as it will run only once even though it was at background process.

Hope it will helps...!!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshekur Rahman Molla AsikView Question on Stackoverflow
Solution 1 - JavaStephen DoneckerView Answer on Stackoverflow
Solution 2 - JavaJuanView Answer on Stackoverflow
Solution 3 - JavaAlecsView Answer on Stackoverflow
Solution 4 - JavaGilad LevinsonView Answer on Stackoverflow
Solution 5 - JavaSrikanth RoopaView Answer on Stackoverflow
Solution 6 - JavaHammad NasirView Answer on Stackoverflow
Solution 7 - JavaChirag DaveView Answer on Stackoverflow
Solution 8 - JavaAvinash ShindeView Answer on Stackoverflow
Solution 9 - JavaHari_Haran_N_S.View Answer on Stackoverflow