1

I want to save the image in external storage. My function works on android 5 but doesn't work on android 8.

I have android.permission.WRITE_EXTERNAL_STORAGE in Manifest.

private fun saveImageToExternalStorage(finalBitmap: Bitmap) {

         val root =
           Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()
       val myDir = File("$root/saved_images_1")
       myDir.mkdirs()
       val generator = Random()
       var n = 10000
       n = generator.nextInt(n)
       val fName = "Image-$n.jpg"
       val file = File(myDir, fName)
       if (file.exists())
           file.delete()
       try {
           val out = FileOutputStream(file)
           finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)
           out.flush()
           out.close()
       } catch (e: Exception) {
           e.printStackTrace()
       }

       MediaScannerConnection.scanFile(this, arrayOf(file.toString()), null,
           object : MediaScannerConnection.OnScanCompletedListener {
               override fun onScanCompleted(path: String, uri: Uri) {
                   Log.i("ExternalStorage", "Scanned $path:")
                   Log.i("ExternalStorage", "-> uri=$uri")
               }
           })
   }

Wanted to change it with context.contentResolver but can't :( Hope, you will help!

Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
N G
  • 55
  • 7

1 Answers1

0

From SDK version above 23 you need to add something for URI exposure. Extend application class and inside of onCreate() method put below code,

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
    if (Build.VERSION.SDK_INT > 23) {
        builder.detectFileUriExposure();
    }

And in Manifest.xml, change

 <application
    android:name=".YOUR_APPLICATION_CLASS"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

Hope, this will solve your issue.

Exigente05
  • 2,161
  • 3
  • 22
  • 42
  • It does't work(( ` ` ` there is my Manifest file. – N G Oct 07 '19 at 14:02
  • Again throws `java.io.FileNotFoundException: /storage/emulated/0/Pictures/saved_images_1/Image-3730.jpg (No such file or directory)` – N G Oct 07 '19 at 14:04