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方法里面添加如下代码:
需要注意的有两点:
1.在5.0以前和5.0以后notification方法的创建方法有些不同。
2.使用Intent来启动service服务的时候要注意。5.0以后的系统在启动service的时候,除了定义Intent,还需要给Intent指明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 activity/service开机后自动运行 (转)
- Android XMPP Service (Google Talk) + Google Map == Follow Me
- communicate with service on android
- 系出名门Android(4) - 活动(Activity), 服务(Service), 广播(Broadcast), 广播接收器(BroadcastReceiver)
- Android service(转)
- 系出名门Android(4) - 活动(Activity), 服务(Service), 广播(Broadcast), 广播接收器(BroadcastReceiver)
- Jollen 的 Android 教学(9): 启动 Service - startService()
- Android中的BatteryService及相关组件
- Android Service Introduce
- android上怎样让一个Service开机自动启动
- [转]Jollen 的 Android 教學,#9: 啟動 Service - startService()
- Android中的BatteryService及相关组件
- communicate with service on android
- [转]Jollen 的 Android 教學,#10: 如何檢查 Service 是否已啟動?使用 Android 除錯器
- Android如何在Activity和Service之间传递数据
- Android Bind Service机制详解
- [转]Jollen 的 Android 教學,#8: 沒有 UI 的 Service
- Jollen 的 Android 教学(10): 如何检查 Service 是否已启动?使用 Android 除错器
- Android基础 : Android Service[转]
- Android基础 : Android Service[转]