检查外部存储管理器是否被授予另一个应用程序

Check if external storage Manager is granted for ANOTHER app

我需要检查另一个应用程序是否具有外部存储管理器的权限。有

Environment.isExternalStorageManager()

我检查当前应用是否被授权。我如何为另一个应用程序执行此操作?我已经尝试使用

检查权限状态
getPackageManager().checkPermission(Manifest.permission.MANAGE_EXTERNAL_STORAGE, "dk.tacit.android.foldersync.lite")

但它return总是-1,这意味着PERMISSION_DENIED,即使授予了权限。

您可以像这样尝试使用 AppOpsManager class :

try {
        PackageManager packageManager = this.getPackageManager();
        ApplicationInfo info = packageManager.getApplicationInfo("package name",0);
        Log.d("TAG", "onCreate: "+hasPermission(this,info)); 
        
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

现在 hasPermission 功能:

@RequiresApi(api = Build.VERSION_CODES.R)
public static boolean hasPermission(Context context,ApplicationInfo info) {
    boolean granted = false;
    AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
    int mode = appOps.unsafeCheckOpNoThrow(AppOpsManager.permissionToOp("android.permission.MANAGE_EXTERNAL_STORAGE"), info.uid, info.packageName);
    if (mode == AppOpsManager.MODE_DEFAULT)
        granted = (context.checkCallingOrSelfPermission(Manifest.permission.MANAGE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    else
        granted = (mode == AppOpsManager.MODE_ALLOWED);
    return granted;
}

您还必须在清单中声明 QUERY_ALL_PACKAGES 权限:

<uses-permission
    android:name="android.permission.QUERY_ALL_PACKAGES"
    tools:ignore="QueryAllPackagesPermission" />

这里是 DrHowdyDoo 解决方案的更通用版本

fun isExternalStorageManager(
    packageName: String,
    context: Context,
    packageManger: PackageManager
): Boolean {
    return hasPermission(packageName, MANAGE_EXTERNAL_STORAGE, context, packageManger)
}


fun hasPermission(
    packageName: String,
    permission: String,
    context: Context,
    packageManger: PackageManager
): Boolean {
    val granted: Boolean
    val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager

    val info = packageManger.getApplicationInfo(packageName, 0)
    val mode = appOps.unsafeCheckOpNoThrow(
        AppOpsManager.permissionToOp(permission)!!,
        info.uid,
        packageName
    )
    granted = if (mode == AppOpsManager.MODE_DEFAULT) {
        context.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED
    } else {
        (mode == AppOpsManager.MODE_ALLOWED)
    }

    return granted
}

示例:

isExternalStorageManager("dk.tacit.android.foldersync.lite", this, getPackageManager())

你也可以在AndroidManifest.xml中这样添加查询的包:

<queries>
    <package android:name="dk.tacit.android.foldersync.lite" />
</queries>