issues in writing files to sd card in android api 23(marshmallow)

后端 未结 3 1533
醉酒成梦
醉酒成梦 2020-12-22 12:59

i am getting error when i try to download this file in Api 23.it works well in version<23.I have seen similar questions like this,but none of the solution worked for me.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 13:32

    First, I check if I have the permission:

    private static final int REQUEST_WRITE_STORAGE = 112;
    
    boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        ActivityCompat.requestPermissions(parentActivity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_WRITE_STORAGE);
    }
    

    Then check the user's approval:

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode)
        {
            case REQUEST_WRITE_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    //reload my activity with permission granted or use the features what required the permission
                } else
                {
                    Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
                }
            }
        }
    
    }
    

    Refer Link

提交回复
热议问题