如何在前景服务中在Kotlin中创建多个通知

发布于 2025-01-26 07:11:29 字数 4310 浏览 2 评论 0原文

我正在开发一个父母控制应用程序,该应用程序多次通知父母,但是当我尝试使用背景服务创建通知时,它只会生成一个1。

这是我的工作方式:

    fun createNotification(parent_name: String, notificationText:String, id: Int){
    val MchannelId = channelId+id.toString()
    if (Build.VERSION.SDK_INT >= 26) {
        val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel(
                MchannelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            )
        } else {
            TODO("VERSION.SDK_INT < O")
        }
        (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
            channel
        )
    }

    val notificationIntent = Intent(this, TabbedActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(
        this,
        id, notificationIntent, 0
    )
    val notification: Notification = NotificationCompat.Builder(this, "$MchannelId")
        .setContentTitle("Hi $parent_name")
        .setContentText(notificationText)
        .setSmallIcon(R.drawable.icon_child)
        //.setContentIntent(pendingIntent)
        .build()
    startForeground(random_number, notification)
}

我的全方位服务类:

const val TAG2 = "Child Service"
class ParentService: Service() {

val db = FirebaseFirestore.getInstance()
private val channelId = "Notification from Service"
var parent_name = userName
override fun onBind(intent: Intent?): IBinder? = null

//OnBind Function Implementation
init {
    Log.d(TAG2, "Started Service!")
}

//onCreate Method Implementation

override fun onCreate() {
    super.onCreate()

}

//OnStartCommand Override
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    Thread{
        while (true){
            checkStatus()
            Thread.sleep(PARENT_CHECK_TIME)
        }
    }.start()
    return START_STICKY
}

private fun checkStatus() {
    var listOfNames = ""
    var i = 1
    val calendar: Calendar = Calendar.getInstance()
    var list = ArrayList<String>()
    db.collection(LINKED_CHILDS)
        .whereEqualTo(USER_PHONE, userPhone)
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents){
                val startTime: Long = calendar.getTimeInMillis()
                val diff = startTime - (document.data[ACTIVE_STATUS] as Long)
                Log.d("TAG", "Time Difference : $diff")
                Log.d("TAG", "${document.data[USER_NAME].toString()}")
                if (diff> MAX_GAP_TIME){
                    Log.d("TAG", "Entered IFF")
                    list.add(document.data[USER_NAME].toString())
                }
            }

            for (name in list){
                listOfNames = listOfNames + "$i. Your child $name is not active\n"
                i++
                createNotification(parent_name, listOfNames, i)
                Log.d("TAG Notification ID:", "ID: $i")
            }
            Log.d("TAG: ", "$listOfNames")

        }
}


fun createNotification(parent_name: String, notificationText:String, id: Int){
    val MchannelId = channelId+id.toString()
    if (Build.VERSION.SDK_INT >= 26) {
        val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel(
                MchannelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            )
        } else {
            TODO("VERSION.SDK_INT < O")
        }
        (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
            channel
        )
    }

    val notificationIntent = Intent(this, TabbedActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(
        this,
        id, notificationIntent, 0
    )
    val notification: Notification = NotificationCompat.Builder(this, "$MchannelId")
        .setContentTitle("Hi $parent_name")
        .setContentText(notificationText)
        .setSmallIcon(R.drawable.icon_child)
        //.setContentIntent(pendingIntent)
        .build()
    startForeground(id, notification)
}
}

Kinldy让我知道我如何能做使用此背景服务创建多个通知。非常感谢您! Kinldy让我知道如何使用此背景服务来创建多个通知。非常感谢您! Kinldy让我知道如何使用此背景服务来创建多个通知。非常感谢您!

I am working on a parental control app which notify parent multiple times but when I try to create notification with a background service it generates only one 1.

Here is how I do it:

    fun createNotification(parent_name: String, notificationText:String, id: Int){
    val MchannelId = channelId+id.toString()
    if (Build.VERSION.SDK_INT >= 26) {
        val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel(
                MchannelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            )
        } else {
            TODO("VERSION.SDK_INT < O")
        }
        (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
            channel
        )
    }

    val notificationIntent = Intent(this, TabbedActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(
        this,
        id, notificationIntent, 0
    )
    val notification: Notification = NotificationCompat.Builder(this, "$MchannelId")
        .setContentTitle("Hi $parent_name")
        .setContentText(notificationText)
        .setSmallIcon(R.drawable.icon_child)
        //.setContentIntent(pendingIntent)
        .build()
    startForeground(random_number, notification)
}

My Full-Service Class:

const val TAG2 = "Child Service"
class ParentService: Service() {

val db = FirebaseFirestore.getInstance()
private val channelId = "Notification from Service"
var parent_name = userName
override fun onBind(intent: Intent?): IBinder? = null

//OnBind Function Implementation
init {
    Log.d(TAG2, "Started Service!")
}

//onCreate Method Implementation

override fun onCreate() {
    super.onCreate()

}

//OnStartCommand Override
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    Thread{
        while (true){
            checkStatus()
            Thread.sleep(PARENT_CHECK_TIME)
        }
    }.start()
    return START_STICKY
}

private fun checkStatus() {
    var listOfNames = ""
    var i = 1
    val calendar: Calendar = Calendar.getInstance()
    var list = ArrayList<String>()
    db.collection(LINKED_CHILDS)
        .whereEqualTo(USER_PHONE, userPhone)
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents){
                val startTime: Long = calendar.getTimeInMillis()
                val diff = startTime - (document.data[ACTIVE_STATUS] as Long)
                Log.d("TAG", "Time Difference : $diff")
                Log.d("TAG", "${document.data[USER_NAME].toString()}")
                if (diff> MAX_GAP_TIME){
                    Log.d("TAG", "Entered IFF")
                    list.add(document.data[USER_NAME].toString())
                }
            }

            for (name in list){
                listOfNames = listOfNames + "$i. Your child $name is not active\n"
                i++
                createNotification(parent_name, listOfNames, i)
                Log.d("TAG Notification ID:", "ID: $i")
            }
            Log.d("TAG: ", "$listOfNames")

        }
}


fun createNotification(parent_name: String, notificationText:String, id: Int){
    val MchannelId = channelId+id.toString()
    if (Build.VERSION.SDK_INT >= 26) {
        val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel(
                MchannelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            )
        } else {
            TODO("VERSION.SDK_INT < O")
        }
        (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
            channel
        )
    }

    val notificationIntent = Intent(this, TabbedActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(
        this,
        id, notificationIntent, 0
    )
    val notification: Notification = NotificationCompat.Builder(this, "$MchannelId")
        .setContentTitle("Hi $parent_name")
        .setContentText(notificationText)
        .setSmallIcon(R.drawable.icon_child)
        //.setContentIntent(pendingIntent)
        .build()
    startForeground(id, notification)
}
}

Kinldy let me know how I can create multiple Notifications using this background service. Thank You so much in advance!
Kinldy let me know how I can create multiple Notifications using this background service. Thank You so much in advance!
Kinldy let me know how I can create multiple Notifications using this background service. Thank You so much in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稀香 2025-02-02 07:11:29

如果您创建一个非通知通知,它将显示您的通知。永久通知将用于您的服务在后台运行。

@RequiresApi(Build.VERSION_CODES.O)
    private fun createNotification() {
        val intent = Intent(this, TabbedActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent: PendingIntent =
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        val notification = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.icon_child)
            .setContentTitle("Hi $parent_name")
            .setContentText(notificationText)
            .setAutoCancel(true)               
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
        with(NotificationManagerCompat.from(this)) {
            notify(notifManagerId, notification.build())
            notifManagerId++
        }
        parmanentNotification()
    }

这是永久通知不会丢失,被销毁将使服务永久运行

private fun parmanentNotification() {
        val notification=NotificationCompat.Builder(this,channelId)
            .setSmallIcon(R.drawable.icon_child)
            .setContentTitle("Hi $parent_name")
            .setContentText("Application service running in the background")
            .build()
        startForeground(1,notification)
    }

If you create a non-persistent notification, it will show your notifications. The permanent notification will be used for your service to run in the background.

@RequiresApi(Build.VERSION_CODES.O)
    private fun createNotification() {
        val intent = Intent(this, TabbedActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent: PendingIntent =
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        val notification = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.icon_child)
            .setContentTitle("Hi $parent_name")
            .setContentText(notificationText)
            .setAutoCancel(true)               
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
        with(NotificationManagerCompat.from(this)) {
            notify(notifManagerId, notification.build())
            notifManagerId++
        }
        parmanentNotification()
    }

this is a permanent notification will not be lost and destroyed will keep the service running permanently

private fun parmanentNotification() {
        val notification=NotificationCompat.Builder(this,channelId)
            .setSmallIcon(R.drawable.icon_child)
            .setContentTitle("Hi $parent_name")
            .setContentText("Application service running in the background")
            .build()
        startForeground(1,notification)
    }
◇流星雨 2025-02-02 07:11:29

在这种情况下,您没有创建常见的Notification,您正在运行服务,该必须在屏幕上具有前景表示。因此活动可见或粘附,修复Notification,您现在显示

它可以使用类似代码拥有很多Notification s,但不要使用开始向他们展示,而是使用notificationmanager,最好是compat版本,

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(uniqueId, notification);

或者就像您在创建频道内部 Insern Insern Insern Insere 时已经在使用它一样:(getSystemService(notification_service)作为notificationmanager).notify(...)

前景相关Notification notification 是粘性的,只要service在后台工作,他们被“绑在一起”。其他通知 s可能被配置为粘性或可滑动,还应在某些channel(每个孩子?per chand?)上发布。请注意,如果您显示另一个粘性通知,则必须通过代码自行发布它,只需杀死服务就不会像与前景相关的<<<代码>通知

一些

you aren't creating a common Notification in this scenario, you are running a Service, which must have a foreground representation on screen. So Activity visible or sticked, fixed Notification, and you are showing it

Now you can have much Notifications using similar code, but don't show them using startForeground, instead use NotificationManager, preferably compat version

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(uniqueId, notification);

or just like you are using it already when creating channel inside if: (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).notify(...)

foreground-related Notification is sticky and lives as long as Service works in background, they are "tied". other Notifications may be configured to be sticky or swipeable, also should be posted on some own Channel (per child? per action?). Note that if you show yet another sticky Notification then you have to release it by own through code, just killing Service won't dismiss it as it does with foreground-related Notification

some DOC in here, read carefully, all answers are there

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文