17.4前台服务
前台服务是被认为是用户已知的正在运行的服务,当系统需要释放内存时不会优先杀掉该进程。前台进程必须发一个 notification 在状态栏中显示,直到进程被杀死。
因为前台服务会一直消耗一部分资源,但不像一般服务那样会在需要的时候被杀掉,所以为了能节约资源,保护电池寿命,一定要在建前台服务的时候发notification ,提示用户。当然,系统提供的方法就是必须有 notification 参数的,所以不要想着怎么把 notification 隐藏掉。
@Override
publicint onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification noti = newNotification.Builder(this)
.setContentTitle("Title")
.setContentText("Message")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendingIntent)
.build();
startForeground(12346, noti);
return Service.START_STICKY;
}
startForeground() 方法就是将服务设为前台服务,参数12346就是这个通知唯一的id,只要不为0即可。
(转自:http://www.tuicool.com/articles/iu22QnF)

前台服务在Android中被视为用户可见的运行服务,即使在系统资源紧张时也不会轻易被终止。由于其持续消耗资源,因此在启动前台服务时必须显示状态栏通知,以告知用户并节约资源。通过调用`startForeground()`方法并传入通知对象来创建前台服务,通知不可隐藏,用于提供用户体验。
442

被折叠的 条评论
为什么被折叠?



