Foggy day

[Android] PACKAGE_USAGE_STATS 권한 획득 본문

Android

[Android] PACKAGE_USAGE_STATS 권한 획득

jinhan38 2023. 9. 26. 23:00

UsageStatsManager 클래스를 사용하기 위해 PACKAGE_USAGE_STATS  권한을 요청해야 했습니다. 

 

 

 

1. manifest에 permission 추가

    <uses-permission
        android:name="android.permission.PACKAGE_USAGE_STATS"
        tools:ignore="ProtectedPermissions" />

 


2. 런타임 권한 요청

private fun checkPermissionUsage(): Boolean {
    val appOps = applicationContext
        .getSystemService(APP_OPS_SERVICE) as AppOpsManager
    val mode = appOps.checkOpNoThrow(
        AppOpsManager.OPSTR_GET_USAGE_STATS,
        Process.myUid(), applicationContext.packageName
    )
    val granted = if (mode == AppOpsManager.MODE_DEFAULT) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            applicationContext.checkCallingOrSelfPermission(
                Manifest.permission.PACKAGE_USAGE_STATS
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            true
        }
    } else {
        (mode == AppOpsManager.MODE_ALLOWED)
    }
    return granted
}