Search code examples
androidkotlinandroidxandroid-jetpack

How to get instance in Kotlin with Context.getSystemService(Class)


In Google Android Kotlin documentation, Every now and then there is a below line present in android documentation that: Instances of this class must be obtained using Context.getSystemService(Class)

For example:

Instances of this class must be obtained using Context.getSystemService(Class) with the argument AppOpsManager.class or Context.getSystemService(String) with the argument Context.APP_OPS_SERVICE.

Can someone please clarify what this is and how do I create a instance for class AppOpsManager.

Usually we can create instance like: val use = AppOpsManager()

Please help and explain the above Context.getSystemService().

Thank You.


Solution

  • From Android Developer documentation:

    AppOpsManager

    API for interacting with "application operation" tracking.

    This API is not generally intended for third party application developers; most features are only available to system applications.

    Instances of this class must be obtained using Context.getSystemService(Class) with the argument AppOpsManager.class or Context.getSystemService(String) with the argument Context.APP_OPS_SERVICE.

    To create an instance of this class you must use getSystemService from a context instance.

    val appOpsManager: AppOpsManager? = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager?
    

    If your minSdkVersion is 23 then you can use this code instead.

    val appOpsManager: AppOpsManager? = getSystemService(AppOpsManager::class.java)