由于Android8.0版本開始攻礼,應(yīng)用的后臺功能被大幅削減睡互,服務(wù)隨便可能被系統(tǒng)殺死,為了能保持服務(wù)長期運行舰涌,使用前臺服務(wù)猖任。
class MyService : Service(){
override fun onCreate() {
super.onCreate()
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val notificationChannel = NotificationChannel("my_service", "前臺服務(wù)通知", NotificationManager.IMPORTANCE_DEFAULT)
manager.createNotificationChannel(notificationChannel)
}
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = 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(pendingIntent)
.build()
startForeground(1,notification)
}
}
這樣,在服務(wù)創(chuàng)建的時候就會在手機狀態(tài)欄出現(xiàn)服務(wù)通知瓷耙,不會被系統(tǒng)不明不白殺死朱躺,又能讓用戶自己控制刁赖。
另外在Android9.0開始,使用前臺服務(wù)需要進行權(quán)限聲明长搀。
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />