安卓前台服务

1.前台服务和后台服务的区别

  1. 前台可见而后台不可见,可见是指前台服务必须在状态栏中发送一条通知,告知用户当前服务在运行,而后台服务是没有的。
  2. 前台服务在内存不足的情况下,不会被系统杀死,而后台服务会。前台服务只有被终止或者在UI界面主动移除才能杀死。
  3. 在安卓9及以上的版本,后台服务在UI不可见的情况下,只会工作大约1分钟的时间后挂掉。

因此,传统的后台服务已经不能满足长时间的工作,只能将后台服务升级为前台服务。

2.前台服务和后台服务的实现区别

  • 后台服务需要实现:

startService(Intent)、onCreate()、onStartCommand(Intent,int,int)、onDestroy();

  • 前台服务需要实现:

startForegroundService(Intent)、onCreate()、onStartCommand(Intent,int,int)、onDestroy();

启动服务后台和前台调用的函数是不一样,同时在onStartCommand还需要实现

NotificationManager

NotificatoinChannel

NotificationCompat.Builder

startForeground(int,Notification);

 2.1.NotificationManager

        NotificationManager用于获取系统的通知服务

NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

 2.2.NotificationChannel

        NotificationChannel定义了通知的通道

NotificationChannel channel = new NotificationChannel(notificationId,notificationName,NotificationManager.IMPORTANCE_HIGH);

第一个参数notificationId:String类型,通道的唯一标识符,自定义。

第二个参数notificationName:String类型,通道的名称,自定义。

第三个参数NotificationManager.IMPORTANCE_HIGH:通道的显示优先级,这个是高优先级,另外的还有:

IMPORTANCE_DEFAULT、IMPORTANCE_LOW、IMPORTANCE_MAX、IMPORTANCE_MIN等等

        定义了通道channel后,下一步执行创建通道,需要用到前面的系统通知服务

notificationManager.createNotificationChannel(channel);

 2.3.NotificationCompat.Builder

        创建通道后,需要构建该通道要发送什么通知

NotificationCompat.Builder builder =new NotificationCompat.Builder(this,"channelId") .setContentTitle("running")

.setContentText("don't close")

.setSmallIcon(R.drawable.ic_notification_icon)

.setChannelId(notificationId);
 

第一个参数this:组件实例,这里的this是前台服务的实例,一般写this就行。

第二个参数"channelId":和前面定义通道时的ID一致。

下面的设置参数:

setContentTitle:设置通知的标题

setContentText:设置通知的文本

setSmallIcon:设置通知的图标

setChannelID:设置通知的通道,可不写

2.4.startForeground

        通道和通知都设置好后,就可以显示通知了

this.startForeground(NOTIFICATION_ID, builder.build());


第一个参数NOTIFICATION_ID:Int类型,通知的唯一标识,自定义。

第二个参数builder.build():builder是一个构建通知的变量,需要通过调用build()将这个通知转变成Notification对象,这样才能显示。

3.onStartCommand返回值

  1. START_STICKY
  2. START_NOT_STICKY
  3. START_REDELIVER_INTENT
  4. START_STICKY_COMPATIBILIT

一般知道前两个就行,第一个挂掉会重启,第二个不会 ,over。

  • 20
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值