Reputation: 51
private void saveImage(Bitmap bitmap){
try {
String path = Environment.getExternalStorageDirectory().toString();
Toast.makeText(getActivity(), path, Toast.LENGTH_SHORT).show();
OutputStream fOut = null;
File file = new File(path, mWallpaper.getId().toString() + ".jpg");
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (MalformedURLException e) {
Toast.makeText(getActivity(), "Error saving wallpaper. MAL", Toast.LENGTH_SHORT).show();
} catch (IOException e1) {
Toast.makeText(getActivity(), "Error saving wallpaper.", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
}
I added this to my AndroidManifests:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I am trying to save an image to /storage/emulated/0/.
EDIT
int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
permissionCheck);
}
}
I've added this to onCreate() for my fragment but I still not a request.
Upvotes: 1
Views: 12403
Reputation: 470
if (Build.VERSION.SDK_INT >= 23) {
int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
Do this if you are using >=api 23. After this add your code. With this code you ask run-time permission from the user.
Requesting Permissions at Run Time Documentation from official Android site
Upvotes: 6
Reputation: 488
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},23
);
}
}
try this also you can follow folling link http://www.theappguruz.com/blog/runtime-permissions-in-android-marshmallow
Upvotes: 0
Reputation: 225
Another solution is to use
getApplicationContext().getFilesDir().getPath()
rather than
Environment.getExternalStorageDirectory()
If you implement this solution, you do not need to add any permission to Manifest because your files are saved in Application directory, not SD Card.
Upvotes: 3