繁体   English   中英

无法获得从Assets文件夹复制sdcard中的文件的权限

[英]Can't get permission to copy file in sdcard from assets folder

在Android中,我创建以下程序

MainActivity.java

    public class MainActivity extends AppCompatActivity {

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

        TextView tvContent = (TextView) findViewById(R.id.tvContent);

        try {
            InputStream file = getResources().getAssets().open("hello.txt");


            if (file != null) {

                Toast.makeText(this, "File Exists", Toast.LENGTH_LONG).show();

                String mytext = "";

                while (file.available() > 0) {
                    mytext = mytext + (char) file.read();
                }

                //tvContent.setText("path: " + Environment.getExternalStorageDirectory() + "/hello.txt");

                tvContent.setText("path: " + System.getenv("SECONDARY_STORAGE") + "/hello.txt");

                byte b[] = mytext.getBytes();

                //OutputStream os = new FileOutputStream(Environment.getExternalStorageDirectory() + "/hello.txt");
                OutputStream os = new FileOutputStream(new File(System.getenv("SECONDARY_STORAGE") + "/hello.txt"));

                os.write(b);
                os.close();

                file.close();

                Toast.makeText(this, "write Success.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "File not exists", Toast.LENGTH_LONG).show();
            }

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

而且我还要向AndroidManifest.xml文件添加写权限

AndroidManifest.xml中

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.assignment.androidapp16">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

上面的程序返回正确的路径/storage/extSdCard/hello.txt但没有将文件复制到此路径,我得到以下错误

W/System.err: java.io.FileNotFoundException: /storage/extSdCard/hello.txt: open failed: EACCES (Permission denied)

当我为内部存储执行此操作时,它将起作用,这意味着它将文件复制到内部存储,但不在sdcard中。

在最新版本的Android中,您必须向用户请求权限。

您可以看到以下内容: https : //developer.android.com/training/permissions/requesting#java

要请求权限,您可以执行以下操作:

// Define a number code for your permission
private final static int MY_PERMISSIONS_REQUEST_WRITE = 42
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.WRITE_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

    // Permission is not granted
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // 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; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_REQUEST_WRITE);

        // MY_PERMISSIONS_REQUEST_WRITE is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
} else {
    // Permission has already been granted
}

为了处理以上代码的结果,请尝试以下操作:

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE: {
            // 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.
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request.
    }
}

如果您有任何疑问,请随时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM