APP开发实战69-前台服务

来源:互联网 发布:淘宝计划书范文 编辑:程序博客网 时间:2024/05/20 19:18

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)


0 0
原创粉丝点击