【问题标题】:Can't get permission to copy file in sdcard from assets folder无法从 assets 文件夹中复制 sdcard 中的文件
【发布时间】:2019-02-22 15:36:08
【问题描述】:

在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 copy assets


    【解决方案1】:

    在最新版本的 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.
        }
    }
    

    如果您有任何问题,请随时提出。

    【讨论】:

      猜你喜欢
      • 2011-06-23
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      相关资源
      最近更新 更多