创建不被杀死的service

    

          service 在android app里 应用 越来越多,特别是联网的app中,无论app是否启动。总须要一个service来维护与后台数据的连接。接收服务端的推送,获取及时的数据信息。

   但是 service 总是在后台不知不觉的别系统回收 或者被 一些优化软件 给 “优化”了,怎么解决问题?

  

    查资料 找到了  Service对象的onStartCommand(Intent,int,int)方法 。此方法介绍:

  

  

onStartCommand有4种返回值:

START_STICKY:假设service进程被kill掉,保留service的状态为開始状态,但不保留递送的intent对象。随后系统会尝试又一次创建service。因为服务状态为開始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。假设在此期间没有不论什么启动命令被传递到service。那么參数Intent将为null。

START_NOT_STICKY:“非粘性的”。使用这个返回值时,假设在运行完onStartCommand后。服务被异常kill掉,系统不会自己主动重新启动该服务。

START_REDELIVER_INTENT:重传Intent。使用这个返回值时,假设在运行完onStartCommand后。服务被异常kill掉,系统会自己主动重新启动该服务,并将Intent的值传入。

START_STICKY_COMPATIBILITY:START_STICKY的兼容版本号,但不保证服务被kill后一定能重新启动。



写个简单的验证程序 看看service 被kill掉后 是否会又一次启动:


public class AutoRunService extends Service {

	private static AutoRunService msService = null;
	private Thread mThread;
	private static boolean isRun;
	private static float num=0;
	@Override
	public void onCreate() {
		super.onCreate();
		Log.d("mservice", "onCreate");
		   msService = this;
		   isRun=true;
		  
			num=0;
			if(mThread==null){
				mThread=new Thread(runnable);
			}
			if(!mThread.isAlive()){
				mThread.start();
			}
	}
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
   
	 @Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		  Log.d("mservice", "onStartCommand");
		 return START_STICKY;
	}
	 
	 @Override
	public void onStart(Intent intent, int startId) {
		 Log.d("mservice", "onStart");
		super.onStart(intent, startId);
		
		
	}
	 
	 @Override
	public void onDestroy() {
			Log.d("mservice", "onDestroy");
		super.onDestroy();
	  //  restartService(this);
	    msService=null;
	    isRun=false;
	}
	 
	 public static AutoRunService getService() {
	        return msService;
	    }
	 
	 public Runnable runnable=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(isRun){
				SystemClock.sleep(1000);
				num+=1;
				 Log.d("mservice", "i am run  times="+num);
			}
		}
	};
	 
}


  启动service:

  

  

protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	Log.d("mservice", "activity onCreate");
	Intent intent =new Intent(this, AutoRunService.class);
	this.startService(intent);
}

 启动 程序  有log 输出:


 


  杀死  service;

   

  


等待了一段时间   service 果然又一次启动:




看重新启动时间 和杀死 service时间间隔 30秒 ,多试了几次   重新启动时间在 0-300秒之间, 測试手机 是 htc one。理论上来说 重新启动时间是不确定的,所以假设想做更

安全的保障。建议 加上 开机 和解锁的 广播接收。在那里再做进一步的service 启动, 假设要求不高。上面的就可以满足。

原文地址:https://www.cnblogs.com/wgwyanfs/p/6875813.html