gpt4 book ai didi

android - 向同一 Activity 中的两个不同函数请求 WRITE_EXTERNAL_STORAGE 权限

转载 作者:行者123 更新时间:2023-11-29 23:22:15 24 4
gpt4 key购买 nike

takeScreenshot 和 saveAsPDF 我有两个不同的函数,它们都需要 WRITE_EXTERNAL_STORAGE 权限。但是我如何在 onRequestPermissionsResult 中为同一 Activity 中的相同权限创建一个切换案例,因为 requestCode 在这两种情况下都是相同的。

最佳答案

您可以像下面这样创建单独的类来检查和请求许可 ->

public class PermissionCheck {

private static final String TAG = PermissionCheck.class.getSimpleName();

private Context context;
private static final int EXTERNAL_WRITE_PERMISSION_CODE = 620;
private static final int CAMERA_PERMISSION_CODE = 335;

public PermissionCheck(Context context) {
this.context = context;
}

// Check Required Permissions...
public boolean CheckRequestedPermission(Context context, String CheckRequiredPermission) {
return ContextCompat.checkSelfPermission(context, CheckRequiredPermission) == PackageManager.PERMISSION_GRANTED;
}

// To Request Permission...
private void requestPermission(final Context context, final String RequestedPermission, final int PermissionCode) {
if (!CheckRequestedPermission(context, RequestedPermission)) {
ActivityCompat.requestPermissions((Activity) context, new String[]{RequestedPermission}, PermissionCode);
}
}


// Just add Permission Code that you required to get permissions and call this method...
public void AskPermission(int RequestCode) {
switch (RequestCode) {
case EXTERNAL_WRITE_PERMISSION_CODE:
requestPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE, EXTERNAL_WRITE_PERMISSION_CODE);
break;
case CAMERA_PERMISSION_CODE:
requestPermission(context, Manifest.permission.CAMERA, CAMERA_PERMISSION_CODE);
break;
}
}
}

并询问您想要的任何权限并在 Activity 或 fragment 中实现 OnRequestPermissionResult,如下所示。

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case EXTERNAL_WRITE_PERMISSION_CODE:
Log.d(TAG, "onPermissionResult : Permission Granted? " + IsExternalWritePermissionGranted);
// changing value based on permission Deny/Accept
IsExternalWritePermissionGranted = permissionCheck.CheckRequestedPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
break;
case CAMERA_PERMISSION:
// changing value based on permission Deny/Accept
IsCameraPermissionGranted = permissionCheck.CheckRequestedPermission(this, Manifest.permission.CAMERA);
break;
}
}

请注意,您从 Activity/fragment 传递到 PermissionCheck 的权限代码应该与 PermissionCheck 类中的相同。

关于android - 向同一 Activity 中的两个不同函数请求 WRITE_EXTERNAL_STORAGE 权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54102971/

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