gpt4 book ai didi

android - 在 kotlin 中启用和禁用广播

转载 作者:行者123 更新时间:2023-11-30 00:24:51 27 4
gpt4 key购买 nike

我编写了这段代码来启用和禁用广播:

        val broadcastState = when(state){
true -> {PackageManager.COMPONENT_ENABLED_STATE_ENABLED}
false -> {PackageManager.COMPONENT_ENABLED_STATE_DISABLED}
}

val component:ComponentName=ComponentName(this,DateChangeReceiver::class)
packageManager.setComponentEnabledSetting(component,
broadcastState,PackageManager.DONT_KILL_APP)

但是 Android Studio 给出了一些错误,直到我将 component 更改为:

val component:ComponentName=ComponentName(this,DateChangeReceiver::class.java)

基于 this link它应该用于检索对象的 Java 类,但我所有的类都在 kotlin 中。所以我想知道我这样做是否正确。

最佳答案

它给你错误是因为 ComponentName类需要一个上下文和一个 Java 类。由于你的类(class)是用 Kotlin 编写的,你应该按照你说的去做:

DateChangeReceiver::class.java

DateChangeReceiver::javaClass

如果 ComponentName 需要一个 Kotlin 类,那么没有 .java 就没有问题

您将使用一些 Java 库来解决这个问题。

同时检查 this关于 Kotlin 中的反射。如那里所述:

Note that a Kotlin class reference is not the same as a Java class reference. To obtain a Java class reference, use the .java property on a KClass instance.

关于android - 在 kotlin 中启用和禁用广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45577792/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com