前台 Service

    普通的 service 优先级比较低,当系统内存不足时,就有可能会回收掉正在后台运行的服务,如果希望服务一直运行而不被回收,则应该使用前台服务。

    前台服务的特点是,会有一个正在运行的图标在状态栏显示,下拉状态栏会有更详细的信息,和通知的效果很相似。

    创建前台服务,只需在 onCreate 中创建通知 Notification,然后调用 startForeground(notificationId, notification)

public int onStartCommand(Intent intent, int flags, int startId) {
    // 在API11之后构建Notification的方式
    Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
    Intent nfIntent = new Intent(this, MainActivity.class);
    builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0))
            .setContentTitle("下拉列表中的Title") // 设置下拉列表里的标题
            .setContentText("要显示的内容") // 设置上下文内容
            .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher))
            .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

    Notification notification = builder.build(); // 获取构建好的Notification
    notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音

    startForeground(110, notification);// 开始前台服务
    return START_NOT_STICKY;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值