如何在异常时正确重启 Android 服务?

How to properly restart an Android service at exception?

我正在尝试开发一个 Android 可以在异常情况下自动重启的服务。

  1. 我尝试在 onStartCommand 方法上添加 return START_STICKY;。但由于异常不会导致服务崩溃,所以不会自动重启。
  2. 我也试过How to restart service in android to call service oncreate again中提到的方法,比如拼了下面的代码,但是调用onDestory()后,只执行了onCreate(),没有执行onStartCommand()
    stopService(new Intent(this, YourService.class));
    startService(new Intent(this, YourService.class));
    

现在,服务如下所示:

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

如代码所示,我希望 PostServiceIOException 被捕获时正确重启。

使用这个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).