我就是想做个笔记而已,给自己看看而已
第一步:
面向Android 9(API级别28)或更高版本并使用前台服务的应用必须请求 FOREGROUND_SERVICE
权限
so先来个权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
然后启动一个前台服务
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)
最后你发现,死活就是tm的没开起来,还崩溃了,哈哈啊啊啊哈哈
然后再看看,发现还需要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)
}
就是这个小混蛋创建了什么通道
然后调用
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)
}
然后发现你的前台服务就这么简单愉快的启动起来了,至于能不能保活我就不懂了,等待验证了
反正搞了这么多都是为了保活
注意:Notification.Builder(baseContext, "1232155654686578343")和NotificationChannel("1232155654686578343", name, importance)
这两个是要一样的
其实不懂的看官网,比网上哪些乱七八糟的靠谱多了,百度百度 .... 摆渡摆渡..... 全是一个抄一个.....
网友评论