Android 6.0 Marshmallow. Cannot Write to Sd Card

Android M write to SD Card - Permission Denied

As suggested by @CommonsWare here we have to use the new Storage Access Framework provided by android and will have to take permission from user to write SD card file as you said this is already written in the File Manager Application ES File Explorer.

Here is the code for Letting the user choose the "SD card" :

startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), requestCode);

which will look somewhat like this :

Sample Image

And get the Document path in pickedDirand pass further in your copyFile block
and use this path for writing the file :

public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode != RESULT_OK)
return;
else {
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
copyFile(sdCard.toString(), "/File.txt", path + "/new", pickedDir);
}
}


public void copyFile(String inputPath, String inputFile, String outputPath, DocumentFile pickedDir) {

InputStream in = null;
OutputStream out = null;
try {

//create output directory if it doesn't exist
File dir = new File(outputPath);
if (!dir.exists()) {
dir.mkdirs();
}

in = new FileInputStream(inputPath + inputFile);
//out = new FileOutputStream(outputPath + inputFile);

DocumentFile file = pickedDir.createFile("//MIME type", outputPath);
out = getContentResolver().openOutputStream(file.getUri());

byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();


// write the output file (You have now copied the file)
out.flush();
out.close();
} catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}

Is it possible to write on portable mounted SDcard? (Android 6 marshmallow)


Is it possible to write on portable mounted SDcard?

Not via File, FileOutputStream, and related file-specific classes.

You are welcome to use ACTION_OPEN_DOCUMENT on Android 4.4+, allowing the user to choose the content to work with via the Storage Access Framework. You can use the Uri that you get back to get an InputStream and, later, an OutputStream to use to read and write the content.

How to write to SD Card in Android 6.0 without asking runtime permission?

You can achieve that when you set in your project's Gradle file the compileSdkVersion not bigger than 22.

Important! When you deploy a version of your app to Google Play store which was compiled against a version bigger than 22, you can never ever switch back to a version below 23. You cannot even switch back to the last stable version if this version used and SDK version lower than 23. You will get an exception in Google Play Store then. It will not allow it.

(This happened to me some days ago, I accidently set a version bigger than 22, deployed it to Google Play, and suddenly I had lots of crashes because Android 6.0+ didn't have the used permission and I didn't ask for it because it was not implemented in code. But I was also not able to switch back to the previous working version in Google Play. So I had to quickly implement the new permission model but was not even able to test it since I don't have Android 6.0 devices and the emulators are a total crap and slow. Now I have 3 apps in store where I don't know how they behave on Android 6.0+. I get no crashes anymore so I guess my implementation is correct)

issues in writing files to sd card in android api 23(marshmallow)

Please check below solution, hope it will work properly for you.

 public void startDownload(View v) 
{
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED){

startDownloading();

} else {

requestForLocationPermission();
}
}


private void requestForLocationPermission()
{

if (ActivityCompat.shouldShowRequestPermissionRationale(activity,Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
}
else {

ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_REQUEST_CODE);
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
startDownloading();
}
break;
}
}


public void startDownloading()
{
Uri uri=Uri.parse("http://oursite/pictures/image.jpg");


Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.mkdirs();

lastDownload = mgr.enqueue(new DownloadManager.Request(uri)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("Pictures")
//.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
"aadhar.jpg"));

v.setEnabled(false);
//findViewById(R.id.query).setEnabled(true);
}


Related Topics



Leave a reply



Submit