我正在尝试开发可在异常情况下自动重启的Android服务。
return START_STICKY;
方法上添加onStartCommand
。但是由于该异常不会导致服务崩溃,因此不会自动重启。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
才能正确重启。
答案 0 :(得分:1)
使用此 START_REDELIVER_INTENT
public static final int START_REDELIVER_INTENT
如果要从
onStartCommand(Intent, int, int):
返回,则常量 服务的进程在启动时被杀死(从中返回后onStartCommand(Intent, int, int))
,然后将其安排为 重新启动,最后一次传递的意图通过重新传递给它onStartCommand(Intent, int, int).