如何在异常情况下正确重启Android服务?

时间:2019-04-24 13:11:15

标签: android android-things

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

  1. 我尝试在return START_STICKY;方法上添加onStartCommand。但是由于该异常不会导致服务崩溃,因此不会自动重启。
  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));
    }
}

如代码中所示,我希望PostService被捕获时IOException才能正确重启。

1 个答案:

答案 0 :(得分:1)

使用此 START_REDELIVER_INTENT

public static final int START_REDELIVER_INTENT
  

如果要从onStartCommand(Intent, int, int):返回,则常量   服务的进程在启动时被杀死(从中返回后   onStartCommand(Intent, int, int)),然后将其安排为   重新启动,最后一次传递的意图通过重新传递给它   onStartCommand(Intent, int, int).