首页 > 解决方案 > IntentService 中的强制停止循环功能

问题描述

我的意图服务中有一个功能类似于倒计时。它被称为counter

在 MainActivity 中执行某些操作后,应将什么添加到 IntentService 或直接添加counter以停止此循环?

class IntentServiceExample : IntentService("Loop_test") {
    private val CHANNEL_ID = "ForegroundService Kotlin"

    companion object {
        val PARAM_OUT_MSG = "None"
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(CHANNEL_ID, "Foreground Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT)
            val manager = getSystemService(NotificationManager::class.java)
            manager!!.createNotificationChannel(serviceChannel)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        createNotificationChannel()

        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0, notificationIntent, 0
        )
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground Service Kotlin Example")
            .setContentText("kylsha")
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(pendingIntent)
            .build()

        startForeground(1, notification)

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

    override fun onHandleIntent(p0: Intent?) {
        Toast.makeText(this,"Service started",Toast.LENGTH_LONG).show()

        val broadcastIntent = Intent()
        broadcastIntent.action = "com.example.intenttest.action.RESPONSE"
        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT)
        sendBroadcast(broadcastIntent)
        counter(broadcastIntent)
    }

    fun counter(bc: Intent){
        for (i in 1..100){
            bc.putExtra(PARAM_OUT_MSG, i.toString())
            Thread.sleep(1000)
            d("number", i.toString())
            sendBroadcast(bc)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopSelf()

    }
}

标签: androidkotlinandroid-intentintentservice

解决方案


在类中创建一个变量。创建一个设置器以将变量设置为 true。在您的 rcounter 例程中,检查正在设置的变量。

private val cancelCounter = false
public fun setToCancel() {
    cancelCounter = true
}

/*Stuff*/

fun counter(bc: Intent){
    for (i in 1..100){
        if (cancelCounter) {
            cancelCounter = false
            break
        }
        bc.putExtra(PARAM_OUT_MSG, i.toString())
        Thread.sleep(1000)
        d("number", i.toString())
        sendBroadcast(bc)
    }
}

您可能无法从 main 直接访问该对象 - 如果没有,那么您应该使用单例模式创建此类;)

我没有在 kotlin 中编写足够的代码,以至于现在“正确的方式”可以做到这一点,但是有一些指向正确方式的链接: https ://blog.mindorks.com/how-to-create-a-singleton-class-in -kotlin https://medium.com/swlh/singleton-class-in-kotlin-c3398e7fd76b

这两个链接都有一些关于他们为什么在结构模式中做出决定的信息,以及实现背后的代码如何工作的一些信息;)


推荐阅读