diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a07473b..dbc90d1 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,8 @@ + + ) : RecyclerView.Adapter() { @@ -36,24 +42,48 @@ class ImageAdapter(private val imageUrls: List) : RecyclerView.Adapter + downloadImage(imageUrl, holder.itemView.context) + } } private fun downloadImage(url: String, context: Context) { + Toast.makeText(context, "Downloading...", Toast.LENGTH_SHORT).show() + Glide.with(context) .asBitmap() .load(url) .into(object : SimpleTarget() { override fun onResourceReady(resource: Bitmap, transition: Transition?) { - // Save the image to the app's internal storage - val file = File(context.filesDir, "downloaded_image.jpg") - try { - val fileOutputStream = FileOutputStream(file) - resource.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream) - fileOutputStream.flush() - fileOutputStream.close() - Toast.makeText(context, "Image downloaded successfully", Toast.LENGTH_SHORT).show() - } catch (e: IOException) { - e.printStackTrace() - Toast.makeText(context, "Error downloading image", Toast.LENGTH_SHORT).show() + // Save the image to the Downloads folder using MediaStore + val contentValues = ContentValues().apply { + put(MediaStore.Images.Media.DISPLAY_NAME, "downloaded_image.jpg") // File name + put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg") + put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/") // Save to the Downloads folder + } + + // Insert the image into MediaStore + val uri = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues) + + uri?.let { imageUri -> + try { + // Open an output stream to write the image to the Downloads folder + val outputStream: OutputStream? = context.contentResolver.openOutputStream(imageUri) + outputStream?.use { + resource.compress(Bitmap.CompressFormat.JPEG, 100, it) // Save the image as JPEG + Toast.makeText(context, "Image downloaded successfully", Toast.LENGTH_SHORT).show() + val intent = Intent(Intent.ACTION_VIEW).apply { + // Use the Uri where the image was saved + setDataAndType(uri, "image/jpeg") // MIME type for images + flags = Intent.FLAG_GRANT_READ_URI_PERMISSION + } + //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(createChooser(intent, "Open image with")) + + } + } catch (e: Exception) { + e.printStackTrace() + Toast.makeText(context, "Error downloading image", Toast.LENGTH_SHORT).show() + } } } })