EACCESS Permission denied in Android

后端 未结 4 939
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 12:28

While writing file in External SD card I am getting an error EACCESS permission denied. I have set the permission

4条回答
  •  被撕碎了的回忆
    2020-12-06 13:00

    From API level 19, Google has added API.

    • Context.getExternalFilesDirs()
    • Context.getExternalCacheDirs()
    • Context.getObbDirs()

    Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions. Restricting writes in this way ensures the system can clean up files when applications are uninstalled.

    Following is approach to get application specific directory on external SD card with absolute paths.

    Context _context = this.getApplicationContext();
    
    File fileList2[] = _context.getExternalFilesDirs(Environment.DIRECTORY_DOWNLOADS);
    
    if(fileList2.length == 1) {
        Log.d(TAG, "external device is not mounted.");
        return;
    } else {
        Log.d(TAG, "external device is mounted.");
        File extFile = fileList2[1];
        String absPath = extFile.getAbsolutePath(); 
        Log.d(TAG, "external device download : "+absPath);
        appPath = absPath.split("Download")[0];
        Log.d(TAG, "external device app path: "+appPath);
    
        File file = new File(appPath, "DemoFile.png");
    
        try {
            // Very simple code to copy a picture from the application's
            // resource into the external file.  Note that this code does
            // no error checking, and assumes the picture is small (does not
            // try to copy it in chunks).  Note that if external storage is
            // not currently mounted this will silently fail.
            InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
            Log.d(TAG, "file bytes : "+is.available());
    
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();
        } catch (IOException e) {
            // Unable to create file, likely because external storage is
            // not currently mounted.
            Log.d("ExternalStorage", "Error writing " + file, e);
        }
    }
    

    Log output from above looks like:

    context.getExternalFilesDirs() : /storage/extSdCard/Android/data/com.example.remote.services/files/Download
    
    external device is mounted.
    
    external device download : /storage/extSdCard/Android/data/com.example.remote.services/files/Download
    
    external device app path: /storage/extSdCard/Android/data/com.example.remote.services/files/
    

提交回复
热议问题