I am trying to develop an Android Service that can automatically restart at exceptions.
return START_STICKY;
on the onStartCommand
method. But since the exception will not cause the service to crash, it won't automatically restart.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.
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 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).