I am developing an Android app. In my app, I am saving a bitmap as file. But it is throwing permission denied exception even if I set the right permissions in the manifest file.
This is how I save a bitmap as a file
private void downloadImage(Bitmap bitmap)
{
try{
String fileName = String.valueOf(System.currentTimeMillis())+".jpeg";
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
if(file.exists()){
file.delete();
}
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
Toast.makeText(getBaseContext(),"Image saved to your device",Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
When I save, it is toasting me error like this.
These are all the permissions I set in manifest file.
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Why is that error throwing? How can I correct my code?
You are developing for Android M I guess? For Andorid M you have to get permissions on runtime.
Please look here.
Search for "Android M runtime permissions" and you will find thousands of examples and explanations.