in the mainFest it has
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and for newer OS it checks the permission
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if it does not return true, it will request the permission
ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 5);
and only when it has the permission it will try to create the file
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String sysDownloadPath = directory.getPath();
try {
if (!directory.exists() && !directory.mkdirs()) {
//shouldn't happen in here
/* Checks if external storage is available for read and write */
String state = Environment.getExternalStorageState();
String externalStorageAvailable = (Environment.MEDIA_MOUNTED.equals(state)) ?
"ext-ST available" :
"ext-ST NOT available"; }
} catch (Exception e) { //<=== did not caught exception here
}
String fileName = ‘SD_20170404.pdf’;
String newFilePath = (sysDownloadPath + "/" + fileName);
File newFile = new File(newFilePath);
try {
newFile.createNewFile();// <=== throws at this one
} catch (Exception e) {
fatal Exception: java.lang.Exception: open failed: EACCES (Permission denied), newFile.getPath():/storage/emulated/0/Download/SD_20170404.pdf
It happens (not always but) with OS 5, 6 and 7. any suggestion? thanks!