如何在Kotlin中使用Pending Intent和Broadcast Receivers从Notification Building使用.addAction停止“前台服务”

ef1yzkbh  于 2023-06-24  发布在  Kotlin
关注(0)|答案(1)|浏览(160)

我有一个使用通知管理器的通知生成器,我使用startForegroud()方法实现了一个前台服务。然而,我对如何使用广播接收器使用stopForeground(true)和stopSelf()停止服务感到非常困惑。这是我目前掌握的情况
在我的MyForegroundService类中,我有以下内容。

class MyForegroundServices : Service() {
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Thread {
            while (true) {
                Log.e("Service", "Service is running...")
                try {
                    Thread.sleep(2000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }.start()

        val CHANNELID = "Foreground Service ID"
        val channel = NotificationChannel(
            CHANNELID,
            CHANNELID,
            NotificationManager.IMPORTANCE_LOW
        )

        val foregroundIntent = Intent(this, NotificationReceiver::class.java).apply {
            action = "STOP_FOREGROUND_SERVICE"
            putExtra(EXTRA_NOTIFICATION_ID, 0)
        }
        val foregroundPendingIntent: PendingIntent =
            PendingIntent.getBroadcast(this, 0, foregroundIntent, 0)

        getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
        val notification = Notification.Builder(this, CHANNELID)
            .setContentText("Service is running")
            .setContentTitle("Service enabled")
            .setSmallIcon(R.drawable.ic_launcher_background)
            .addAction(R.drawable.ic_launcher_background, "Stop", foregroundPendingIntent)

        //Any ID will do at the moment
        startForeground(1001, notification.build())

        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(p0: Intent?): IBinder? {
        TODO("Not yet implemented")
    }
}

现在我不知道如何正确地实现pendingIntent,我也不知道在使用Broadcast receivers的receiver类中放置什么

class NotificationReceiver : BroadcastReceiver() {
    override fun onReceive(p0: Context?, p1: Intent?) {
        TODO("Not yet implemented")

    }
}

期待并提前感谢您的帮助。

rsl1atfo

rsl1atfo1#

看起来你的PendingIntent很好。
如果你想让你的BroadcastReceiver停止Service,对onReceive()使用类似这样的方法:

override fun onReceive(context: Context?, intent: Intent?) {
    context.stopService(Intent(context, MyForegroundServices::class.java))
}

如果您还想使用这个BroadcastReceiver来做其他事情,您可以查询传入onReceive()Intent参数,并使用ACTION或“extras”来执行您想要的任何其他功能。

相关问题