APP开发实战69-前台服务

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值