在onStartCommand()方法中返回START_REDELIVER_INTENT,以确保服务断电后能够重启,并且检查服务是否已经运行来防止重复重启。代码示例:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(isServiceRunning()){
return START_NOT_STICKY;
}
//do some work
return START_REDELIVER_INTENT;
}
private boolean isServiceRunning(){
//check if service is already running
}