1.前台服务和后台服务的区别
- 前台可见而后台不可见,可见是指前台服务必须在状态栏中发送一条通知,告知用户当前服务在运行,而后台服务是没有的。
- 前台服务在内存不足的情况下,不会被系统杀死,而后台服务会。前台服务只有被终止或者在UI界面主动移除才能杀死。
- 在安卓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返回值
- START_STICKY
- START_NOT_STICKY
- START_REDELIVER_INTENT
- START_STICKY_COMPATIBILIT
一般知道前两个就行,第一个挂掉会重启,第二个不会 ,over。