您的位置:首页 > 移动开发 > Android开发

Android中Service白色保活

2016-12-21 23:50 183 查看
android中一般都是在service进行处理一些耗费时间的任务,或者进行一些长时间的任务,但是android中service优先级特别低,所以当系统中出现内存不足的情况下,service是会被率先回收的。会使得长时间任务被中断。

android系统为了使得service能够在后台常驻,推荐的方法是使用前台通知来保证服务的运行。一般称为白色保活手段,除了白色保活手段,还有灰色和黑色保活手段。不过灰色保活是使用的系统漏洞,已经被android系统修复。黑色保活手段是指另开进程,每隔一定时间检查service是否存活,如果被回收,那么就重新开启service,以此来保证service永远不会被杀死。

白色保活手段是指启动service时会发出一个notification消息在通知栏,用于和service绑定,这样提高service的优先级,被推迟收回,保证service存活。

service的onCreate方法里面添加如下代码:

//定义一个notification
Notification.Builder builder = new Notification.Builder(this);
builder.setContentInfo("补充内容");
builder.setContentText("正在运行...");
builder.setContentTitle("进行标题");
builder.setSmallIcon(R.mipmap.appicon);
builder.setTicker("新消息");
builder.setAutoCancel(true);
builder.setWhen(System.currentTimeMillis());
Intent notificationIntent = new Intent(this, TaskDetailActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder.setContentIntent(pendingIntent);
Notification notification = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
notification = builder.build();
}else{
notification = builder.getNotification();
}
//把该service创建为前台service
startForeground(1, notification);


需要注意的有两点:

1.在5.0以前和5.0以后notification方法的创建方法有些不同。

2.使用Intent来启动service服务的时候要注意。5.0以后的系统在启动service的时候,除了定义Intent,还需要给Intent指明service所在的包名。不然会出现问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android