进程保活,service保活

一、onStartCommand方法,返回START_STICKY

  START_STICKY 在运行onStartCommand后service进程被kill后,那将保留在开始状态,但是不保留那些传入的intent。不久后service就会再次尝试重新创建,因为保留在开始状态,在创建     service后将保证调用onstartCommand。如果没有传递任何开始命令给service,那将获取到null的intent。

二、提升service优先级      

  在AndroidManifest.xml文件中对于intent-filter可以通过android:priority = "1000"这个属性设置最高优先级,1000是最高值,如果数字越小则优先级越低,同时适用于广播。

三、提升service进程优先级

  Android中的进程是托管的,当系统进程空间紧张的时候,会依照优先级自动进行进程的回收。Android将进程分为6个等级,它们按优先级顺序由高到低依次是:

   1.前台进程( FOREGROUND_APP)

   2.可视进程(VISIBLE_APP )

   3.次要服务进程(SECONDARY_SERVER )  

   4.后台进程 (HIDDEN_APP)

   5.内容供应节点(CONTENT_PROVIDER)

   6.空进程(EMPTY_APP)

当service运行在低内存的环境时,将会kill掉一些存在的进程。因此进程的优先级将会很重要,可以使用startForeground 将service放到前台状态。这样在低内存时被kill的几率会低一些。


public class MyService extends Service {
	private static final String TAG = "wxx";
 
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
 
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.d(TAG, "MyService: onCreate()");
		
		//定义一个notification
        Notification notification = new Notification();        
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, "My title", "My content", pendingIntent); 
        //把该service创建为前台service
        startForeground(1, notification);
	}
 
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d(TAG, "MyService: onStartCommand()");
		return super.onStartCommand(intent, flags, startId);
	}
 

四、onDestory里面发送广播重启service

service +broadcast  方式,就是当service走ondestory的时候,发送一个自定义的广播,当收到广播的时候,重新启动service;

	             Intent intent = new Intent();
			   	intent.setAction(ACTION_Broad);
				sendBroadcast(intent);



 
public class TestBroadcast extends BroadcastReceiver {
 
	@Override
	public void onReceive(Context context, Intent intent) {
		
		Toast.makeText(context, "广播我已经启动服务了", Toast.LENGTH_SHORT).show();
		System.out.println("广播我已经启动服务了");
		
		Intent service = new Intent(context,TestService.class);
		service.setAction(TestActivity.ACTION_Service);
//		在广播中启动服务必须加上startService(intent)的修饰语。Context是对象
		context.startService(service);
	}
 
}

五、Application加上Persistent属性

六、监听系统广播判断Service状态

通过系统的一些广播,比如:手机重启、界面唤醒、应用状态改变等等监听并捕获到,然后判断我们的Service是否还存活,别忘记加权限啊。

七、双进程Service

让2个进程互相保护,其中一个Service被清理后,另外没被清理的进程可以立即重启进程

八、联系厂商,加入白名单

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!

发布了77 篇原创文章 · 获赞 3 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/haiyang497661292/article/details/85318708