如何检查片段中的权限


92

我想检查片段中的权限。

我的代码:

        // 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
    }
}

Answers:


50

我已经完成以下检查片段中的权限的操作。

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
如果用户尚未授予许可,我们仍然需要寻求许可。
卡兰·塔卡

17
请记住,如果执行此操作,则请求许可权结果将出现在启动片段的活动中。有关在片段中接收结果的方法,请参见ThetNaing Mizo的答案。
lsrom '18

253

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

活动:

ActivityCompat.requestPermissions(this, permissionsList, REQUEST_CODE);

对于片段:

requestPermissions(permissionsList, REQUEST_CODE);

Fragment requestPermissions需要Android M,但在FragmentCompat中可用于较早的API版本。
布莱恩·怀特

20
在片段中请求许可的正确方法
塔伦(Tarun)

requestPermissions是使用元帅并升级sdk
hamid

76

片段具有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();
        }
    }
}

Fragment requestPermissions需要Android M,但可以在FragmentCompat中使用。
布莱恩·怀特

4

onRequestPermissionsResult在活动中而不是在片段中被调用。尝试改写onRequestPermissionsResult活动。


尽管这是事实,但它缺乏解释为何如此以及如何解决它的方法-如何弄成onRequestPermissionResult碎片。ThetNaing Mizo在回答中解释了零散的结果的解释和接收方式。
lsrom '18 -4-18

谢谢,我想知道为什么我的代码无法在Fragment中工作
Azizjon Kholmatov '19

4

使用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 {

}

4

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


3

什么工作对我来说是调用onRequestPermissionsResult的方法活动中,其片段中实现,而不是调用它本身的片段。在片段的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();
            }

        }
});

在有助于实现片段的Activity中,在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;
    }
}


0

我在使用checkSelfPermission()时绊倒了Fragment,想知道什么Context是null的最佳方法(特定于Kotlin)……我应该使用!!还是其他方式

我根据iosched中发现的代码进行了其他处理。看看下面的示例,并记住,在将Fragment附加到之前ActivityContext将会为null。

private fun fineLocationPermissionApproved(): Boolean {

    val context = context ?: return false

    return PackageManager.PERMISSION_GRANTED == checkSelfPermission(
        context,
        Manifest.permission.ACCESS_FINE_LOCATION
    )
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.