-1

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.

enter image description here

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
  • Possible duplicate of [Android permission doesn't work even if I have declared it](http://stackoverflow.com/questions/32635704/android-permission-doesnt-work-even-if-i-have-declared-it) – Mike M. Nov 02 '16 at 13:44
  • `file.delete()` Check the return value before continuing with your code. – greenapps Nov 02 '16 at 13:55

1 Answers1

3

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.

beta
  • 131
  • 1
  • 1
  • 3