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!
Related
I have developed a android system application to copy file from /sdcard/download/test.txt to /cache/xyz/ location.
I am able to copy the file to /cache/ , but bot into /cache/xyz/ location ,
Getting below error :
java.io.FileNotFoundException: /cache/xyz/test.txt: open failed: EACCES (Permission denied)
File packageFile = new File(Environment.getDownloadCacheDirectory() + "/xyz/test.txt");
File downloadedFile = new File(Environment.getExternalStorageDirectory() + "/test.txt");
if (packageFile.exists()) {
Log.d(TAG, "TEST -> File in Cache Exists");
} else {
Log.d(TAG, "TEST -> File in Cache is Empty");
}
packageFile.canWrite();
if (downloadedFile.exists()) {
Log.d(TAG, "TEST -> packageFile in downloadedFile Exists");
FileChannel source = null;
FileChannel dest = null;
try {
source = (new FileInputStream(downloadedFile)).getChannel();
dest = (new FileOutputStream(packageFile)).getChannel();
count += dest.transferFrom(source, count, size-count);
catch (Exception e) {
Log.d(TAG, "TEST -> Failed to copy update file into internal storage: " + e);
}
} else {
Log.d(TAG, "TEST -> File DO NOT Exists");
}
Manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
For API 23+ you need to request the read/write permissions even if they are already in your manifest.
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* #param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
via: Exception 'open failed: EACCES (Permission denied)' on Android
I am creating an app that requier an app-specific file that I called "conf.cfg" for example. this file need to be read by my application to create some object etc... the body of the file look like that :
#activation, level, type, regex or array
0, "critic", 0,"\\d{4}\\w\\d{3}"
1, "critic", 1, [word1,word2]
1,"minor", 0,"\\d{2}-\\w{3}-\\d{4}\\s?\\/?\\s?\\d{2}:\\d{2}"
Doing my research I found that there is two type of Storage in android :
Internal storage :
Internal storage is best when you want to be sure that neither the user nor other apps can access your files.
External storae :
External storage is the best place for files that don't require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.
As I want the user to be able to edit/download/upload/USE this file, External Storage seems to be a good choice. However on Developper Android they said :
Caution: The external storage might become unavailable if the user removes the SD card or connects the device to a computer. And the files are still visible to the user and other apps that have the READ_EXTERNAL_STORAGE permission. So if your app's functionality depends on these files or you need to completely restrict access, you should instead write your files to the internal storage.
Caution: Files on external storage are not always accessible, because users can mount the external storage to a computer for use as a storage device. So if you need to store files that are critical to your app's functionality, you should instead store them on internal storage.
As this file need to be always available and is critical to my app's functionality
So... Internal Storage seems to be better. But I need the user to see and be able to use the file. And here I'm stuck.
Anyone has an idea of where and how to put/create this file ?
EDIT : following #greenapps answer
heer is a piece of code I've wrote. I use the getExternalFilesDir(null) command to write and store my file
String folderName = "Innovation";
String confFileName = "conf.txt";
String commentSymbol = "#";
String commentLine = commentSymbol + " activation, level, type , regex or array";
File storage = getExternalFilesDir(null);
File folder = new File(storage, folderName);
File conf = new File(folder, confFileName);
Log.d(TAG, "Folder action!");
if (!folder.exists()) {
if (folder.mkdirs()) {
Log.d(TAG, "Created : " + folder.getAbsolutePath());
} else {
Log.e(TAG, "folder not created!");
}
}
Log.d(TAG, "File action!");
if (!conf.exists()) {
try {
Log.d(TAG, "opening...");
FileOutputStream fos = new FileOutputStream(conf);
fos.write(commentLine.getBytes());
fos.close();
Log.d(TAG, "Created : " + conf.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
if (conf.exists()) {
Log.d(TAG, "File exist at : " + conf.getAbsolutePath());
}
the file is created, as shown by the last log
Created : /storage/emulated/0/Android/data/com.aralex.innovation/files/Innovation/conf.txt
But when I search the file with the native file explorer application of the phone, I can't find it. I can go to the file folder but the folder "Innovation/" is hidden.
This is a problem because I want the file to be visible.
Phone : Samsung s7, s7edge, s9+
Default File Explorer Icon
Default File Explorer Oppened
Well I finally found an answer myself.
On this post Android create folders in Internal Memory #prodev specify that Environment.getExternalStorageDirectory() is a good place, because the file will be accessible and :
note that ExternalStorage in Environment.getExternalStorageDirectory() does not necessarily refers to sdcard, it returns phone primary storage memory
it requires permissions (only for build version >= M) :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
So here is a code to answer my problem (it ask permission on runtime) :
private ArrayList<Rule> ruleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
// Check for the storage permission before accessing the camera. If the
// permission is not granted yet, request permission.
if (hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
|| Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
ruleList = createRules();
} else {
requestStoragePermission();
}
}
private boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
Log.d(TAG, "Checking permission : " + permission);
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
Log.w(TAG, "not granted : " + permission);
return false;
} else {
Log.d(TAG, "granted : " + permission);
}
}
}
return true;
}
/**
* Handles the requesting of the storage permission. This includes
* showing a "Snackbar" errorMessage of why the permission is needed then
* sending the request.
*/
private void requestStoragePermission() {
Log.w(TAG, "Storage permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_EXTERNAL_PERM);
return;
}
final Activity thisActivity = this;
View.OnClickListener listener = view -> ActivityCompat.requestPermissions(thisActivity, permissions,
RC_HANDLE_EXTERNAL_PERM);
Snackbar.make(findViewById(android.R.id.content), R.string.permission_storage_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, listener)
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != RC_HANDLE_EXTERNAL_PERM) {
Log.d(TAG, "Got unexpected permission result: " + requestCode);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Storage permission granted");
// We have permission
ruleList = createRules();
return;
}
Log.e(TAG, "Permission not granted: results len = " + grantResults.length +
" Result code = " + (grantResults.length > 1 ? grantResults[0] + " " + grantResults[1] : grantResults.length > 0 ? grantResults[0] : "(empty)"));
DialogInterface.OnClickListener listener = (dialog, id) -> finish();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Assisting Tool")
.setMessage(R.string.no_storage_permission)
.setPositiveButton(R.string.ok, listener)
.show();
}
private ArrayList<Rule> createRules() {
Log.d(TAG, "=========================READING FILE======================");
ArrayList<Rule> ruleList = new ArrayList<>();
String folderName = "Innovation";
String confFileName = "conf.txt";
String commentSymbol = "#";
String commentLine = commentSymbol + " activation, level, type , regex or array";
File storage = Environment.getExternalStorageDirectory();
File folder = new File(storage, folderName);
File conf = new File(folder, confFileName);
Log.d(TAG, "Folder action!");
if (!folder.exists()) {
if (folder.mkdirs()) {
Log.d(TAG, "Created : " + folder.getAbsolutePath());
} else {
Log.e(TAG, "folder not created!");
}
}
Log.d(TAG, "File action!");
if (!conf.exists()) {
try {
Log.d(TAG, "opening...");
FileOutputStream fos = new FileOutputStream(conf);
fos.write(commentLine.getBytes());
fos.close();
Log.d(TAG, "Created : " + conf.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
if (conf.exists()) {
Log.d(TAG, "File exist at : " + conf.getAbsolutePath());
} else {
Log.e(TAG, "The file doesn't exist...");
}
}
Now it create a app-specific file
/storage/emulated/0/Innovation/conf.txt
that is accessible by user !
So external storage.
No internal as file explorers have no access to your apps private internal memory.
You could use getExternalFilesDir(null) as then you dont need read and write permissions
I want to save a picture file from Internet to my mobile. I have used both Internet and externalstorage Permission in AndroidManifest file. But it gives an error given below. I think it is because my device don't have an SD CARD. If so then I want to know how to store in Internal storage.
myError
java.io.FileNotFoundException:
/storage/emulated/0/Pictures/GettyImages-460712009-560x450.jpg: open
failed: EACCES (Permission denied Caused by:
android.system.ErrnoException: open failed: EACCES (Permission denied)
Below is my code.
try {
URL urlobj = new URL(url);
connection= (HttpURLConnection) urlobj.openConnection();
inputStream=connection.getInputStream();
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/"+ Uri.parse(url).getLastPathSegment());
FileOutputStream fileOutputStream = new FileOutputStream(file);
int reed = -1;
byte[] buffer = new byte[1024];
// if no data is return -1 keep reading until -1
while( ( reed=inputStream.read(buffer) )!= -1){
fileOutputStream.write(buffer,0,reed);
}
You are getting Permission denied Exception because you are not implementing Run Time permission for Devices having Android Marshmallow and above version ..
This is how you can achieve this :
Add following permission to manifest like earlier :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Match if the user has already granted the permission. If yes, skip asking for permission and continue with your work else ask user for permission :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 2909);
} else {
// your code
}
} else {
// your code
}
Permission result callback:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 2909: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("Permission", "Granted");
} else {
Log.e("Permission", "Denied");
}
return;
}
}
}
To save an image in internal memory use this code.
You should add permission in you manifast file<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You need run time permission in marshmallow and above version, for that use Amit sharma Answer.
Here is the code to save a file in Default picture directory.
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
For mode details please check this Link
I tried everything to write on external SD card on Android 6.0, but I am not able to write on it.
I did research on stackoverflow and found lot of things but none works. Here is my code
String extPath = System.getenv("SECONDARY_STORAGE") + "/Android/data/com.gvm.externalstorage.externalstoragetest/";
File file = new File(extPath,"myFiles");
if (!file.exists()) {
boolean dirResult = file.mkdirs();
Log.e("Directory Exist", dirResult + " Directory created");
} else {
Log.e("Directory Exist", "Exist");
Log.e("Direcotry Path",file.getAbsolutePath());
}
//String displayname = fileName.replace("%20", " ");
File outputFile = new File(file, "mytest5.txt");
outputFile.createNewFile();
This code works on Android 5.0 but not on Android 6.0.
Then I tried this path as well, and that gives me permission error, I have set all permission and managed code for runtime permission as well.
/mnt/media_rw/6AC9-083B
File write failed: java.io.IOException: open failed: EACCES (Permission denied)
If anyone can help me it would be great as I am trying this since last 3 days.
Thanks,
Anvesh
After long hard work I figured out a solution. In Android 6.0 it's not going to give you SD Card path always using this:
System.getenv("SECONDARY_STORAGE")
or this
Environment.getExternalStorageDirectory()
So I retrieved external SD Card path using this
File[] fs = context.getExternalFilesDirs(null);
String extPath = "";
// at index 0 you have the internal storage and at index 1 the real external...
if (fs != null && fs.length >= 2)
{
extPath = fs[1].getAbsolutePath();
Log.e("SD Path",fs[1].getAbsolutePath());
}
Rest everything will remain same for permission and all.
Thanks to those who helped me.
From API 23+(6.0) you need to request the read/write permissions even if they are already in your manifest known as Requesting Permissions at Run Time.
from docs
Beginning in Android 6.0 (API level 23), users grant permissions to
apps while the app is running, not when they install the app. This
approach streamlines the app install process, since the user does not
need to grant permissions when they install or update the app. It also
gives the user more control over the app's functionality; for example,
a user could choose to give a camera app access to the camera but not
to the device location. The user can revoke the permissions at any
time, by going to the app's Settings screen.
java
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* #param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I think u should check your app permission first, to make sure your storage permission has been turned on.
If there's no storage permission:
Please check if u use this permission in your AndroidManifest
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
If the storage permission has been turned off:
Please check your runtime permission, maybe u can refer to this code
private void checkPermissions() {
if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return;
}
final List<String> permissionsList = new ArrayList<String>();
permissionsList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
permissionsList.add(Manifest.permission.WRITE_CALENDAR);
permissionsList.add(Manifest.permission.READ_PHONE_STATE);
int permissionCheckLocation = ContextCompat.checkSelfPermission(IntroductionActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
int permissionCheckStorage = ContextCompat.checkSelfPermission(IntroductionActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionCheckCalendar = ContextCompat.checkSelfPermission(IntroductionActivity.this, Manifest.permission.WRITE_CALENDAR);
int permissionCheckPhoneState = ContextCompat.checkSelfPermission(IntroductionActivity.this, Manifest.permission.READ_PHONE_STATE);
boolean locationPermission=permissionCheckLocation == PackageManager.PERMISSION_GRANTED?true:false;
boolean storagePermission=permissionCheckStorage == PackageManager.PERMISSION_GRANTED?true:false;
boolean calendarPermission=permissionCheckCalendar == PackageManager.PERMISSION_GRANTED?true:false;
boolean phoneStatePermission=permissionCheckPhoneState == PackageManager.PERMISSION_GRANTED?true:false;
boolean shouldShowLocationPermission=ActivityCompat.shouldShowRequestPermissionRationale(IntroductionActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
boolean shouldShowStoragePermission=ActivityCompat.shouldShowRequestPermissionRationale(IntroductionActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
boolean shouldShowCalendarPermission=ActivityCompat.shouldShowRequestPermissionRationale(IntroductionActivity.this, Manifest.permission.WRITE_CALENDAR);
boolean shouldShowPhoneStatePermission=ActivityCompat.shouldShowRequestPermissionRationale(IntroductionActivity.this, Manifest.permission.READ_PHONE_STATE);
if (permissionCheckLocation == PackageManager.PERMISSION_GRANTED && permissionCheckStorage == PackageManager.PERMISSION_GRANTED
&& permissionCheckCalendar == PackageManager.PERMISSION_GRANTED && permissionCheckPhoneState == PackageManager.PERMISSION_GRANTED){
return;
}else if(((!locationPermission&&!shouldShowLocationPermission)||(!storagePermission&&!shouldShowStoragePermission)
||(!calendarPermission&&!shouldShowCalendarPermission)||(!phoneStatePermission&&!shouldShowPhoneStatePermission))&&appContext.localCheckPermission){
showMessageOKCancel("You need to allow access these permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 1);
}
});
}else{
ActivityCompat.requestPermissions(IntroductionActivity.this, permissionsList.toArray(new String[permissionsList.size()]), 0);
}
}
If still have problem, please try to change your file path :
String fileName="mytest5.txt";
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/com.gvm.externalstorage.externalstoragetest/");
if (!folder.exists()) {
try {
folder.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + folder);
}
}
File logFile = new File(folder, fileName);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + logFile);
}
}
Best regards. I hope this can help u
#Anvesh Another reliable method i'm using:
/**
* Get external storage path use reflect on android 6.0 device.
* Source code:
* https://github.com/android/platform_frameworks_base/blob/master/core/java/android/os/storage/StorageVolume.java
*
* #param removable the sdcard can remove or not, true means external sdcard, false means
* internal sdcard.
* #return path of sdcard we want
*/
public static String getStoragePath(boolean removable) {
WinZipApplication application = WinZipApplication.getInstance();
Context mContext = application.getApplicationContext();
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean mRemovable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (removable == mRemovable) {
return path;
}
}
} catch (Exception e) {
return null;
}
return null;
}
After a lot of research I found ABSOLUTE SOLUTION. IT WORKS.
public boolean checkStorage() {
File[] fs = con.getExternalFilesDirs(null);
if (fs.length == 2)
return true;
else
return false;
}
The issue is to save image to the storage
This code worked fine, but not with Android 6 and N
What do I need to fix here?
Or as an option - using another example for saving to internal\external files
public void saveImage(Bitmap icon) {
File ff;
File file = new File(android.os.Environment.getExternalStorageDirectory(), "Folder Name");
ff = new File(file.getAbsolutePath() + file.separator + imageName + ".jpg");
if(ff.exists()){
Log.i("sharing", "File exist SD");
} else{
try {
File f = null;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
if (!file.exists()) {
file.mkdirs();
}
Log.i("sharing", "File exist Internal");
f = new File(file.getAbsolutePath() + file.separator + imageName + ".jpg");
}
FileOutputStream ostream = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And permissions from Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Thanx
You should put the uses-permission-sdk-23 tag and set the permission you want.
Then
You should check whether the permission is granted or not by calling the checkSelfPermission and pass the permission name as argument
If the permission is not granted you should gain the permissions by calling the requestPermissions method and pass the permissions names as string array and the request code
After that
A dialog will be shown to user and ask them if the permission is granted or not
Then a interface onRequestPermissionResult will be called and you should implement this into your activity class
After that
You can gain access to the requested permissions if the user granted it
I added permissions for android sdk > 22
This code works perfectly
if (ContextCompat.checkSelfPermission(HomeActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(HomeActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},23
);
}