I'm using a rooted phone to take screen shots using shell and I want to open the image I took (it is visible in file explorer and it exists since I check it with File.exists()). I asked for this permissions:
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="package.name.example">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
...
In code I check if permissions are granted:
MainActivity.java
//Check permissions
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)) {
// permissions already given
} else {
// request permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 101);
}
So on button click I take a screen shot using shell:
long startMiliseconds = System.currentTimeMillis();
Process captureScreen = Runtime.getRuntime().exec("su",null,null);
OutputStream os = captureScreen.getOutputStream();
os.write(("/system/bin/screencap -p "+"/sdcard/screencaps/ss"+ startMiliseconds +".png").getBytes("ASCII"));
os.flush();
os.close();
This will ask me for super user permission and take a screen shot of screen. When I try to access created image programaticly (I first check if file exists and it does):
String filePath = "/sdcard/screencaps/ss"+ startMiliseconds +".png";
Bitmap bMap = BitmapFactory.decodeFile(filePath);
img.setImageBitmap(bMap);
(img is an ImageView label) I get this error:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /sdcard/screencaps/ss1515070630835.png: open failed: EACCES (Permission denied)
EDIT:
Seems it is permission related. I have changed min SDK and target SDK to 23.
I changed handling of permission request to:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//granted permission
System.out.println("INFO: 1");
} else {
//not granted permission
System.out.println("INFO: 2");
}
if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//granted permission
System.out.println("INFO: 3");
} else {
//not granted permission
System.out.println("INFO: 4");
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
And even if I press Allow in popup I get INFO: 2 and INFO: 4 which means that my permissions are not accepted. Sorry for not using loging.
EDIT 2:
Seems like the problem is error I get after permission popup: Screen overlay detected
Hello your assuming sdcard is always /sdcard... Yes I know that sounds stupid. Try
Environment.getExternalStorageDirectory()+File.separator+"/screencaps/ss"
On small edit:
You haven't said if you have a popup appear on your screen? That might be you issue as well. User has to give app permission.
If so read this and look at the examples
https://developer.android.com/training/permissions/requesting.html
**Edit : **
This is a huge shot in the dark but here is something you could put in your getting image method, where you parse the image to imageview
galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
Setting up a gallery intent. Or maybe adding
<uses-permission android:name="android.permission.CAMERA" />
Related
I added the permissions to write access to the external storage device in the Manifest, and granted them in my Android phone. I even ask for them at execution time if they don't exist.
However, I always get this exception:
java.io.FileNotFoundException: /storage/emulated/03b3d97bd-5186-4506-97dc-9994b7ce0761 (Permission denied)
Do you have an idea of why?
Code
try {
if (Build.VERSION.SDK_INT >= 23) {
int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + image_uuid);
byte[] buffer = new byte[1024];
int bytesRead;
BitmapDrawable bitmapDrawable = (BitmapDrawable) temp.getDrawable();
etc. etc. etc.
And in the manifest file:
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You write file in sd card before you get permission.You must wait for the result of granting permission by using below code:
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE/*1 in here*/: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
// write file here
} else {
// permission denied
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
see here
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 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
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.