前台Service 和普通Service 最大的区别就在于:它一直会有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。
从Android 8.0 系统(代号:Oreo;版本:8.0.0;API 级别:26)开始,只有当应用保持在前台可见状态的情况下,Service 才能保证稳定运行,一旦应用进入后台之后,Service 随时都有可能被系统回收。前台Service启动后,即使退出应用程序,MyService 也会一直处于运行状态,而且不用担心会被系统回收。
当然,MyService 所对应的通知也会一直显示在状态栏上面。如果用户不希望我们的程序一直运行,也可以选择手动杀掉应用,这样MyService 就会跟着一起停止运行了。
class MyService : Service() {
...
override fun onCreate() {
super.onCreate()
Log.d("MyService", "onCreate executed")
val manager = getSystemService(Context.NOTIFICATION_SERVICE)
as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"my_service",
"前台Service通知",
NotificationManager.IMPORTANCE_DEFAULT
)
manager.createNotificationChannel(channel)
}
val intent = Intent(this, MainActivity::class.java)
val pi = PendingIntent.getActivity(this, 0, intent, 0)
val notification = NotificationCompat.Builder(this, "my_service")
.setContentTitle("This is content title")
.setContentText("This is content text")
.setSmallIcon(R.drawable.small_icon)
.setLargeIcon(BitmapFactory
.decodeResource(resources, R.drawable.large_icon))
.setContentIntent(pi)
.build()
/**
* 这次在构建Notification对象后并没有使用NotificationManager 将通知显示出来,
* 而是调用了startForeground()方法。
* 调用方法后就会让MyService 变成一个前台Service,并在系统状态栏显示出来。
* 参数:
* 第一个参数是通知的id,类似于notify()方法的第一个参数;
* 第二个参数是构建的Notification对象。
*/
startForeground(1, notification)
}
...
}