尝试写入外部存储时,网页不可用,net :: ERR_ACCESS_DENIED

时间:2018-02-05 19:58:10

标签: android permissions android-external-storage

我正在尝试写入我的Android设备的外部存储器,并认为我包含了所有必要的权限检查。我的代码包括用户按下一个按钮,该按钮写入手机上的文本文件,但每次按下按钮并查看文本文件时都会显示

'网页不可用

位于file:///storage/emulated/0/Notifications/TestFolder/test.txt的网页 无法加载,因为:

净:: ERR_ACCESS_DENIED'

以下是我的代码:

public class MainActivity extends AppCompatActivity {

    Button write_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        isStoragePermissionGranted();

        write_button = (Button)findViewById(R.id.button_write);

        write_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                writeToFile("This is a test","TestFolder","test.txt");
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
            Log.d("TAG","Permission: "+permissions[0]+ "was "+grantResults[0]);
            writeToFile("This is a test","TestFolder","test.txt");
        }
    }

    public  boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.d("TAG","Permission is granted");
                return true;
            } else {

                Log.d("TAG","Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
            Log.d("TAG","Permission is granted");
            return true;
        }
    }

    public void writeToFile(String data, String Dir, String fileName) {

        try {
            File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS) + "/" + Dir);
            Log.d("TAG", "Dir " + dir);
            if (dir.exists() == false) {
                dir.mkdirs();
            }
            final File file = new File(dir, fileName);
            Log.d("TAG", "File Path " + file);
            FileOutputStream fOut = new FileOutputStream(file, true);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fOut);

            outputStreamWriter.append(data);
            outputStreamWriter.flush();
            outputStreamWriter.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

0 个答案:

没有答案