我就是想做個筆記而已,給自己看看而已
第一步:
面向Android 9(API級別28)或更高版本并使用前臺服務(wù)的應(yīng)用必須請求 FOREGROUND_SERVICE 權(quán)限
so先來個權(quán)限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
然后啟動一個前臺服務(wù)
val pendingIntent: PendingIntent =
Intent(this, ExampleActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(this, 0, notificationIntent, 0)
}
val notification: Notification = Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.build()
// Notification ID cannot be 0.
startForeground(ONGOING_NOTIFICATION_ID, notification)
最后你發(fā)現(xiàn),死活就是tm的沒開起來,還崩潰了,哈哈啊啊啊哈哈
然后再看看,發(fā)現(xiàn)還需要tn的什么通道,先不管了,先上代碼:
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.app_name)
val descriptionText = getString(R.string.app_name)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("1232155654686578343", name, importance).apply {
description = descriptionText
}
// Register the channel with the system
notificationManager.createNotificationChannel(channel)
}
就是這個小混蛋創(chuàng)建了什么通道
然后調(diào)用
notificationManager.notify(1, notification)
好了差不多了
完整代碼就是這樣的:
@RequiresApi(Build.VERSION_CODES.O)
fun createNotificationChannel() {
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.app_name)
val descriptionText = getString(R.string.app_name)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("1232155654686578343", name, importance).apply {
description = descriptionText
}
// Register the channel with the system
notificationManager.createNotificationChannel(channel)
}
val pendingIntent: PendingIntent =
Intent(this, MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(this, 0, notificationIntent, 0)
}
val notification: Notification = Notification.Builder(baseContext, "1232155654686578343")
.setContentTitle(getText(R.string.app_name))
.setContentText(getText(R.string.app_name))
.setSmallIcon(R.drawable.ic_back)
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.app_name))
.build()
startForeground(123, notification)
notificationManager.notify(1, notification)
}
然后發(fā)現(xiàn)你的前臺服務(wù)就這么簡單愉快的啟動起來了,至于能不能?;钗揖筒欢?,等待驗(yàn)證了
反正搞了這么多都是為了?;?/p>
注意:Notification.Builder(baseContext, "1232155654686578343")和NotificationChannel("1232155654686578343", name, importance)
這兩個是要一樣的
其實(shí)不懂的看官網(wǎng),比網(wǎng)上哪些亂七八糟的靠譜多了,百度百度 .... 擺渡擺渡..... 全是一個抄一個.....