如何检查片段中的权限

时间:2016-11-23 09:35:34

标签: android android-fragments

我想检查片段内的权限。

我的代码:

        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {


            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        1);



                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }

但在允许或拒绝后未调用onRequestPermissionsResult

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            Log.e("test","0");
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                //yes

                Log.e("test","1");

                Intent intent = new Intent(getActivity(), MapsActivity.class);
                intent.putExtra("latitude", 35.694828);
                intent.putExtra("longitude", 51.378129);
                startActivity(intent);

            } else {
                utilityFunctions.showSweetAlertWarning(getActivity(),r.getString(R.string.str_warning_title_empty),
                        r.getString(R.string.str_you_must_allow_this_permission_toast),
                        r.getString(R.string.str_warning_btn_login));

                Log.e("test","2");
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

10 个答案:

答案 0 :(得分:150)

这就是我做的,它对我有用。谢谢!

活动:

ActivityCompat.requestPermissions(this, permissionsList, REQUEST_CODE);

片段:

requestPermissions(permissionsList, REQUEST_CODE);

答案 1 :(得分:43)

片段有requestPermissions()onRequestPermissionsResult()方法,使用它。

checkSelfPermission()来自ActivityCompat(不需要Activity,只有Context)。

if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    requestPermissions( //Method of Fragment
        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
        REQUEST_PERMISSIONS_CODE_WRITE_STORAGE
    );
} else {
    downloadImage();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == REQUEST_PERMISSIONS_CODE_WRITE_STORAGE) {
        if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            proceedWithSdCard();
        }
    }
}

答案 2 :(得分:30)

我已经完成了检查片段内的权限。

if (ActivityCompat.checkSelfPermission(getContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getContext(),
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
         requestPermissions(getActivity(),
                new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        android.Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_LOCATION);
    } else {
        Log.e("DB", "PERMISSION GRANTED");
    }

答案 3 :(得分:3)

检查 Fragment 的权限(2021 方式)

片段中的 registerForActivityResult() 方法现已弃用。弃用消息建议使用 registerForActivityResult。因此,经过一些试验和错误之后,这是 2021 年的方式:

假设您的片段名称是 AwesomeFragment。然后在构造函数中(准确地说是在片段的 onCreate 方法之前),初始化 ActivityResultLauncher<String[]> activityResultLauncher

java 版本

private ActivityResultLauncher<String[]> activityResultLauncher; 

public AwrsomeFragment() {
 activityResultLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
            @Override
            public void onActivityResult(Map<String, Boolean> result) {
                Log.e("activityResultLauncher", ""+result.toString());
                Boolean areAllGranted = true;
                for(Boolean b : result.values()) {
                    areAllGranted = areAllGranted && b;
                }

                if(areAllGranted) {
                    capturePhoto();
                }
            }
        });
}

然后可能在单击某个按钮时调用 launch 方法:

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        String[] appPerms;
        appPerms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        this.cameraClick.setOnClickListener(v -> {
            this.activityResultLauncher.launch(appPerms);
        });
    }

kotlin 版本

private var activityResultLauncher: ActivityResultLauncher<Array<String>>
init{
this.activityResultLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()) {result ->
        var allAreGranted = true
        for(b in result.values) {
            allAreGranted = allAreGranted && b
        }
        
        if(allAreGranted) {
          capturePhoto()            
        }
    }
}

// --- ---
 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
// ... ... init views / binding... ...
   someBtn.setOnClickListener{
        val appPerms = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
        )
        activityResultLauncher.launch(appPerms)
  }       
}

答案 4 :(得分:2)

在活动中调用

onRequestPermissionsResult而不是片段。请尝试在活动中覆盖onRequestPermissionsResult

答案 5 :(得分:2)

使用Kotlin,您调用requestPermissions(arrayOf(Manifest.permission.THE_PERMISSION_CODE_YOU_WANT), PERMISSION_REQUEST_CODE)并将以下替代添加到片段

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out kotlin.String>, grantResults: IntArray): Unit {

}

答案 6 :(得分:1)

如果您从设置中关闭了应用程序的权限,则无法从代码或您的Android版本低于Marshmallow打开您的权限。

您可以查看此文档 https://developer.android.com/training/permissions/requesting.html 这是一个例子 https://www.learn2crack.com/2015/10/android-marshmallow-permissions.html

答案 7 :(得分:0)

对我有用的是在 activity 中调用 onRequestPermissionsResult 方法,在其中实现了 fragment ,而不是在片段本身中调用它。 在片段的 onCreateView 方法内:

    Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
            }else{
                //Do your work
                fetchMethod();
            }

        }
});

在有助于实现片段的“活动”中,在 onCreate 方法之外:

    @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_MEDIA:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                fetchMethod();

            }else{
                Toast.makeText(getApplicationContext(), "Permission not granted!", Toast.LENGTH_SHORT).show();
            }
            break;

        default:
            break;
    }
}

答案 8 :(得分:0)

Fragment调用requestPermissions方法中处理权限。如果您在片段和包含该片段的活动中都覆盖onRequestPermissionsResult方法,请确保在活动方法中调用super.onRequestPermissionsResult(...),以将调用传播到片段中的onRequestPermissionsResult方法。

答案 9 :(得分:0)

我在checkSelfPermission()中使用Fragment被绊倒了,想知道Context为空(Kotlin特定)的最佳方法是什么...我应该使用{{1 }}或还有其他内容

我根据code I found in iosched和其他人一起去了。看看下面的示例,请记住,在将!!附加到Fragment之前,Activity将为空。

Context