Search code examples
androidandroid-things

How to properly restart an Android service at exception?


I am trying to develop an Android Service that can automatically restart at exceptions.

  1. I have tried adding return START_STICKY; on the onStartCommand method. But since the exception will not cause the service to crash, it won't automatically restart.
  2. I have also tried the methods mentioned in How to restart service in android to call service oncreate again, like putting together the following code, but after onDestory()was called, only onCreate() is executed but not onStartCommand()
    stopService(new Intent(this, YourService.class));
    startService(new Intent(this, YourService.class));
    

Right now, the service looks like this:

public class PostService extends Service {

    site.bdsc.raspberry_gps_test.sim800Cutil.Sim800Manager Sim800Manager;
    private Thread thTestPost;
    private boolean mRunning;
    private static String TAG = "PostService";

    public PostService() {
    }

    @Override
    public void onCreate(){
        //get service
        thTestPost = new Thread(testPost,"testPost");
        Log.d(TAG,"Service on create");
    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        if (!mRunning) {
            // Prevent duplicate service
            mRunning = true;
            Log.d(TAG,"Starting Post Service");
            try {
                Sim800Manager = Sim800ManagerImpl.getService("UART0");
            } catch (IOException e) {
                restartService(); //want to restart service here
            }
            thTestPost.start();
        }else{
            Log.d(TAG,"Duplicated Start Request!");
        }
        return START_STICKY;
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.d(TAG,"Service on destory");
        mRunning = false;
        thTestPost.interrupt();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Runnable testPost = new Runnable() {
        @Override
        public void run() {
         // some code
        }
    };

    private void restartService(){
        stopService(new Intent(this, PostService.class));
        startService(new Intent(this,PostService.class));
    }
}

As shown in the code, I want the PostService to properly restart when IOException is caught.


Solution

  • Use this START_REDELIVER_INTENT

    public static final int START_REDELIVER_INTENT
    

    Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int).