我开发了一个简单的 GPS 跟踪应用程序,它使用前台服务来保持应用程序的运行。会有一个通知显示我的应用程序正在运行,但是如何在徽标旁边隐藏应用程序名称?我只想要徽标而不显示应用程序名称。
问问题
61 次
1 回答
1
要使服务在前台保持活动状态,您可以创建自己的通知并根据需要对其进行自定义。
您可以将此示例代码用作基础。
lateinit var notificationBuilder: Notification
private fun setNotification(title: String, descr: String) {
val pendingIntent = PendingIntent.getActivity(
this, 0, Intent(
this,
MainActivity::class.java
), 0
)
createNotificationChannel()
notificationBuilder = NotificationCompat.Builder(this, "misc")
.setContentTitle(title)
.setContentText(descr)
.setOnlyAlertOnce(true)
.setSmallIcon(R.drawable.ic_nordic_icon)
.setContentIntent(pendingIntent)
.build()
startForeground(1, notificationBuilder)
}
lateinit var manager: NotificationManager
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
"misc",
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
manager = getSystemService(
NotificationManager::class.java
)
manager.createNotificationChannel(serviceChannel)
}
}
并在您的服务中调用它,例如:
setNotification(
"My title",
"A notification description"
)
官方文档在这里。
更新
您可以使用以下配置隐藏通知:
serviceChannel = new NotificationChannel(
"misc",
"Foreground Service Channel",
NotificationManager.IMPORTANCE_UNSPECIFIED
);
notification = new NotificationCompat.Builder(this, "misc")
.setPriority(Notification.PRIORITY_MIN)
.setContentTitle(title)
.setContentText(descr)
.setContentIntent(pendingIntent)
.build();
如果对您有帮助,请记住将您的答案标记为正确。谢谢你。
于 2022-01-11T09:19:25.417 回答