I am downloading images form URL and saving them in pictures directory in folder name unsplash. Now if a user has already downloaded an image I want to show an alert dialog that picture has already been downloaded and if the user wants to download it again. Please help me through it how can I do that.
downloadBtn.setOnClickListener {
if (ContextCompat.checkSelfPermission(
baseContext,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
== PackageManager.PERMISSION_GRANTED
) {
startDownloading(list,position)
} else {
requestDownloadPermission()
}
}
private fun requestDownloadPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
) {
val dialog = AlertDialog.Builder(this)
dialog.setTitle("Permission Required")
dialog.setMessage("Permission Required for downloading this picture." +
"Please go to settings for accessing permission")
dialog.setPositiveButton("Go to setting") { _: DialogInterface, _: Int ->
val openURL = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
openURL.data = Uri.fromParts("package", packageName, null)
startActivity(openURL)
}
dialog.setNegativeButton("cancel") { _: DialogInterface, _: Int -> }
dialog.show()
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
STORAGE_PERMISSION_CODE
)
}
}
private fun startDownloading(list: ArrayList<ImageModel>, position: Int) {
Toast.makeText(this, "Downloading", Toast.LENGTH_SHORT).show()
val downloadList = list[position].urls.raw
val request = DownloadManager.Request(Uri.parse(downloadList))
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_PICTURES,
"/unsplash/${list[position].id}.jpg"
)
.setTitle("Unsplash Images").setAllowedOverMetered(true)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
val manager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
myId = manager.enqueue(request)
var br = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (id == myId) {
Toast.makeText(baseContext, "Downloaded Successfully", Toast.LENGTH_SHORT)
.show()
}
}
}
registerReceiver(br, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
val list = intent.getStringArrayListExtra("FULLIMAGELIST") as ArrayList<ImageModel>
val position = intent.getIntExtra("POSITION", 0)
startDownloading(list,position)
}
} else {
Toast.makeText(baseContext, "Permission Denied", Toast.LENGTH_SHORT).show()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}