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

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.

This question is related to java android service

The answer is


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


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.


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;
    }

}

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...!!


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


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.


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


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


"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());
    

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to service

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058" startForeground fail after upgrade to Android 8.1 Context.startForegroundService() did not then call Service.startForeground() How to restart a windows service using Task Scheduler the MySQL service on local computer started and then stopped Android: keep Service running when app is killed How to create a service running a .exe file on Windows 2012 Server? Start systemd service after specific service? Spring Boot application as a Service SSRS expression to format two decimal places does not show zeros