I try to create a folder in sdcard
File folder = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "folder");
Log.d(TAG, "FOLDER :" +folder);
folder.mkdir();
mkdir always return false. I added permission to manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I can create folder with adb tool.
Phone is Nexus 5 Android 6.0.1
what is wrong with code ?
In android 6.0+ you have to request permission at runtime, so in onCreate() request WRITE_EXTERNAL_STORAGE
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
And add this method (optional):
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted!
} else {
// permission denied!
Toast.makeText(MainActivity.this, "Permission denied to write External storage", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
You can use also Nammu to check the permissions
Related
I'm trying to read a json file from the SDCard in the Phone.(SAMSUNG SM-G532M).
But I can't.
I want to put the file in "Downloads" folder, and make the app to look in that folder in particular, for a particular filename.
But i get a FileNotFoundException.
When I debug the application, the path is different from what i spected.
I get "/storage/emulated/0", but I want to read the Download Folder in the SDCARD.
When i use this sentece:
ruta_sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
and I debug the value, it's ponting to :
/storage/emulated/0/Download
When I try to navigate with Device File Explorer, i get "Opendir Failed: Permission Denied"
What i'm doing wrong ?
I added this line to manifest.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">
</uses-permission>
notes:
Developing un Android Studio 3.2
Phone : Samsung : SM-G532M ( not emulated )
Thanks in advance!
Best Regards
You need to request the runtime.
public static final int READ_EXTERNAL_STORAGE = 112;
protected void readSDcardDownloadedFiles() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
} else {
//Permission is granted
//Call the method to read file.
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Read the files
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
}
I have a problem creating directory on SD card.
AndroidManifest.xml contains neccessary permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application...
Also for Android 6.0 I ask these permissions at runtime:
int permissionCheck1 = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
int permissionCheck2 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck1 != PackageManager.PERMISSION_GRANTED || permissionCheck2 != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_READWRITE_STORAGE);
} else {
init();
}
and waiting for results:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_READWRITE_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
init();
} else {
Toast toast = Toast.makeText(this, "Read / Write storage permissions required", Toast.LENGTH_SHORT);
toast.show();
}
break;
default:
break;
}
}
My application determines two available storages:
internal - /storage/emulated/0
and external (removable SD card) - /storage/6052-CD5B
I create folders using
new File(parentDirectory, newDirectoryName).mkdirs();
Results:
I can create folder inside /storage/emulated/0.
I can create folder inside /storage/6052-CD5B/Android/data/myapp (this is my application folder).
But I can't create folder in /storage/6052-CD5B outside my application folder, e.g. images folder /storage/6052-CD5B/DCIM.
It seems that granted permissions give me access only to application-specific folder. Is it so? If not, how can I finally get write access to other SD card folders?
I'm working on an application built for Android SKD version 22.
In this application folders are created using this way:
String FileDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES) + "/" + app_name + "/" + prefix;
File mediaStorageDir = new File(FileDir);
if (!mediaStorageDir.exists()){
mediaStorageDir.mkdirs();
Log.d("FolderCreation", "created successfully");
}else{
Log.d("FolderCreation" , "Already exists");
}
It was working well until I had to compile and run it on Android 6 (SDK v.23).
Now the folders is not created.
Is there something that has changed with Android 6 regarding the folder "storage/emulated/0"?
Do I have to change the directory when I work on Android 6?
EDIT -> SOLVED
With Android 6 (SDK v23) I must ask the permissions runtime, showing a confirm dialog.
Here the code I use that works.
//create a method that check the permissions
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
In the onCreate():
//list of permissions that you need to ask
String[] permissions = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION};
//use the method to check if the user needs to confirm the permissions
if(!hasPermissions(this,permissions)){
ActivityCompat.requestPermissions(this, permissions, PERMISSION_IDENTIFIER);
}else{
//permission already granted, hooray!
}
Add onRequestPermissionsResult to manage the choose of the user when the dialog is shown:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case PERMISSION_IDENTIFIER:
//your actions
break;
}
}
Android 6 introduced a new version of permission management. Users can now give and take permissions for apps.
See Android - Marshmallow.
Check youre app permissions in the emulator and look out as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
might not be given by the user.
when I try to run this code in marshmallow the folder was not created..
the code is,I tried to run the same code its working fine except marshmallow
File folder = new File(Environment.getExternalStorageDirectory() + "/abcdefg");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdir();
}
if (!success) {
Log.d("", "Folder not created.");
} else {
Log.d("", "Folder created!");
}
Try to add below code in your activity for requesting runtime permission.
Your need to require READ_EXTERNAL_STORAGE permission to create folder(directory) in external storage.
if (ActivityCompat.checkSelfPermission(YourActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_FOR_STORAGE);//REQUEST_FOR_STORAGE=1111
} else {
//Do your stuff here
}
...
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == REQUEST_FOR_STORAGE){
//Do your stuff here
}
}
Hope its help you.
As marshmallow introduce Run time Permission you have to check for the permission
in run time. You can refer here
1.https://developer.android.com/training/permissions/requesting.html
2.https://www.youtube.com/watch?v=iZqDdvhTZj0
3.https://www.youtube.com/watch?v=C8lUdPVSzDk
You have to accept the STORAGE permission group from the user dynamically.
Go with the below link
http://developer.android.com/guide/topics/security/permissions.html
App unable to write to external storage on Android 6.0 (I'm testing on emulator), even after WRITE_EXTERNAL_STORAGE has been granted at runtime; unless the app is killed and restarted.
Snippet from AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
build.gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
......
minSdkVersion 15
targetSdkVersion 23
}
Whenever I need to write to external storage (for backup) I check whether or not I have permission.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
getActivity().getBaseContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_RW_EXTERNAL_STORAGE);
mPendingAction = PendingAction.Backup;
} else {
BackupRestoreService.startBackup(getActivity().getBaseContext());
}
I also have the following
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d("SettingsActivity", "grantResultsLength: " + grantResults.length);
if (requestCode == PERMISSION_REQUEST_RW_EXTERNAL_STORAGE) {
Log.d("SettingsActivity", "grantResultsLength: " + grantResults.length);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
switch (mPendingAction) {
case Backup:
BackupRestoreService.startBackup(getActivity().getBaseContext());
mPendingAction = PendingAction.None;
break;
case Restore:
break;
default:
}
} else {
Toast.makeText(getActivity(),
"Permission denied",
Toast.LENGTH_SHORT).show();
}
}
}
When the permission is granted by user, the following code
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), DIR_MY_PORTFOLIO);
if (!file.mkdirs())
Log.d("Backup", "Unable to create directories");
final String outputFilename = new SimpleDateFormat("'Backup'-yyyyMMdd-hhmmss'.mpb'", Locale.US).format(new Date());
File outputFile = new File(getBackupStorageDir(), outputFilename);
Log.d("Backup", "Can write to file: " + outputFile.canWrite());
Log.d("Backup", "File exists: " + outputFile.exists());
produces
in.whoopee.myportfolio D/Backup: Unable to create directories
in.whoopee.myportfolio D/Backup: Can write to file: false
in.whoopee.myportfolio D/Backup: File exists: false
in.whoopee.myportfolio W/System.err: java.io.FileNotFoundException: /storage/09FD-2F0C/Download/My Portfolio/Backup-20151011-051318.mpb: open failed: EACCES (Permission denied)
If, after the permission is granted, the app is killed and restarted, everything goes perfect and backup file is created in external storage.
Please suggest what I am doing wrong.
Add the following line in onRequestPermissionsResult() method after checking permission grant successfully.
android.os.Process.killProcess(android.os.Process.myPid());
Edit: Check you have set the target sdk version to 23.if You already have done that and it is not working(or you don't want to set it to 23) than you may go with this solution(killing the app process).
Try to emulate a new device (for example a 6.0 x86_64 with Google api's). I had the exact same problem and i resolved it by running on a different emulator.