我正在尝试开发一个可以在异常情况下自动重启的 Android 服务。
- 我尝试在
onStartCommand
方法上添加return START_STICKY;
。但由于异常不会导致服务崩溃,因此不会自动重启。 - 我也尝试过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
被捕获时正确重启。
最佳答案
使用这个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 fromonStartCommand(Intent, int, int))
, then it will be scheduled for a restart and the last delivered Intent re-delivered to it again viaonStartCommand(Intent, int, int).
关于android - 如何在异常时正确重启 Android 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55830886/