【问题标题】:Android: External Write Permissions [duplicate]Android:外部写入权限[重复]
【发布时间】:2018-09-22 17:55:10
【问题描述】:

我一直在尝试从 Android Studio读取和写入文本文件,并不断收到 "Permission denied" 异常。我已经阅读了不同的帖子,但似乎仍然无法解决它。

我的代码:

public void buttonSave(View view) {
    //File directory = new File(path);
    File directoryFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "");
    directoryFile.mkdirs();
    File file = new File(directoryFile, "savefile.txt");
    try {
        file.createNewFile();
    } catch (IOException e) {;}

    eV = (EditText)findViewById(R.id.editText_box);
    String[] editTextValue = eV.getText().toString().split(" ");

    Save(file, editTextValue);
}

public void Save(File file, String[] data){
    FileOutputStream foe = null;
    Toast.makeText(getApplicationContext(), Integer.toString(data.length), Toast.LENGTH_SHORT).show();

    try {
        foe = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
    }
    try {
        for (int i=0; i<data.length; i++){
            foe.write(data[i].getBytes());
            if (i<data.length){
                foe.write("\n".getBytes());
            }
        }
    } catch (IOException e) {};
    try {
        foe.close();
    } catch (IOException e) {};
}

还有我的清单文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="home.learningapp2">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

有什么建议吗?它在模拟器上或在我的手机上运行时不起作用。

【问题讨论】:

标签: android permissions android-permissions ioexception


【解决方案1】:

首先你应该在清单文件中获得权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

然后你应该获得运行时权限,将此方法添加到你的活动中:

private boolean checkPermission() {
    int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
    int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
    return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}

private void requestPermission() {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 100:
            if (grantResults.length > 0) {
                boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                if (locationAccepted && cameraAccepted)
                    Toast.makeText(this, "Permission Granted, Now you can access", Toast.LENGTH_LONG).show();
                else {
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            showMessageOKCancel("You need to allow access to both the permissions",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                        100);
                                            }
                                        }
                                    });
                            return;
                        }
                    }

                }
            }


            break;
    }
}


private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(MainActivity.this)
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", null)
            .create()
            .show();
}

然后改变你的 onCreate() 方法:

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

    if (checkPermission()) {
        Toast.makeText(this, "Permission already granted.", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, "Please request permission.", Toast.LENGTH_LONG).show();
    }

    if (!checkPermission()) {
        requestPermission();
    } else {
        Toast.makeText(this, "Permission already granted.", Toast.LENGTH_LONG).show();
    }

}

你也可以在 kotlin 中看到这个例子:Runtime permission example

【讨论】:

  • 这解决了,非常感谢!
【解决方案2】:

我在不同的许可下使用此代码,但我认为它们是相同的,试试这个:

 public void Save(File file, String[] data){

          public void Save(File file, String[] data){

        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted
        }else {

        FileOutputStream foe = null;
        Toast.makeText(getApplicationContext(), Integer.toString(data.length), Toast.LENGTH_SHORT).show();

        try {
            foe = new FileOutputStream(file);
        }catch (FileNotFoundException e) {Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();}

        try {

            for (int i=0; i<data.length; i++){
                foe.write(data[i].getBytes());
                if (i<data.length){
                    foe.write("\n".getBytes());
                }

            }
        }catch (IOException e) {};

        try {
            foe.close();
        } catch (IOException e) {};
    } }

【讨论】:

    猜你喜欢
    • 2020-10-31
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多