Android marshmallow request permission?

后端 未结 24 2509
無奈伤痛
無奈伤痛 2020-11-21 06:40

I am currently working on an application that requires several \"dangerous\" permissions. So I tried adding \"ask for permission\" as required in Android Marshmallow(API Lev

24条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 07:07

    Try this

    This is the simplest way to ask for permission in Marshmallow version.

     if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED&&ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {
            //TO do here if permission is granted by user
        }
        else
        {
            //ask for permission if user didnot given
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION}, 0);
            }
        }
    

    Note:- Don't forget to add this same permission in manifest file also

     
    
    

    Second Method Code for checking the permission is granted or not?

    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA}, 1);
    

    And override the method

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
             //                    grantResult[0] means it will check for the first postion permission which is READ_EXTERNAL_STORAGE
            //                    grantResult[1] means it will check for the Second postion permission which is CAMERA
                    Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
                }
                else
                    Toast.makeText(this, "Permission not Granted", Toast.LENGTH_SHORT).show();
                return;
            }
        }
    }
    

提交回复
热议问题