如何使用 Context.getSystemService(Class) 在 Kotlin 中获取实例

SVK*_*SVK 5 android kotlin android-jetpack androidx

在 Google Android Kotlin 文档中,Android 文档中偶尔会出现以下一行: 必须使用 Context.getSystemService(Class) 获取此类的实例

例如:

必须使用带有参数 AppOpsManager.class 的 Context.getSystemService(Class) 或带有参数 Context.APP_OPS_SERVICE 的 Context.getSystemService(String) 来获取此类的实例。

有人可以澄清这是什么以及如何为 class 创建实例AppOpsManager

通常我们可以创建如下实例: val use = AppOpsManager()

以上请帮忙解释一下Context.getSystemService()

谢谢。

Nhấ*_*ang 9

来自Android 开发者文档:

应用运营管理器

用于与“应用程序操作”跟踪交互的 API。

此 API 通常不适用于第三方应用程序开发人员;大多数功能仅适用于系统应用程序。

Context.getSystemService(Class)必须使用with 参数 AppOpsManager.classContext.getSystemService(String)with 参数来获取此类的实例 Context.APP_OPS_SERVICE

要创建此类的实例,您必须getSystemService从上下文实例中使用。

val appOpsManager: AppOpsManager? = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager?
Run Code Online (Sandbox Code Playgroud)

如果您的minSdkVersion年龄为 23 岁,则可以使用此代码。

val appOpsManager: AppOpsManager? = getSystemService(AppOpsManager::class.java)
Run Code Online (Sandbox Code Playgroud)