Guest User

MyImageDownloader.kt

a guest
Sep 17th, 2020
3
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class MyImageDownloader {
  2.  
  3.     private var msg: String? = ""
  4.     private var lastMsg = ""
  5.     private var imageUrl = ""
  6.     private lateinit var context: Activity
  7.  
  8.     fun getImage(activity: Activity, url: String) {
  9.         imageUrl = url
  10.         context = activity
  11.         // After API 23 (Marshmallow) and lower Android 10 you need to ask for permission first before save an image
  12.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
  13.             askPermissions(url)
  14.         } else {
  15.             downloadImage(url)
  16.         }
  17.     }
  18.  
  19.     @TargetApi(Build.VERSION_CODES.M)
  20.     fun askPermissions(imageUrl: String) {
  21.         if (ContextCompat.checkSelfPermission(
  22.                 context,
  23.                 Manifest.permission.WRITE_EXTERNAL_STORAGE
  24.             ) != PackageManager.PERMISSION_GRANTED
  25.         ) {
  26.             // Permission is not granted
  27.             // Should we show an explanation?
  28.             if (ActivityCompat.shouldShowRequestPermissionRationale(
  29.                     context,
  30.                     Manifest.permission.WRITE_EXTERNAL_STORAGE
  31.                 )
  32.             ) {
  33.                 // Show an explanation to the user *asynchronously* -- don't block
  34.                 // this thread waiting for the user's response! After the user
  35.                 // sees the explanation, try again to request the permission.
  36.                 AlertDialog.Builder(context)
  37.                     .setTitle("Permission required")
  38.                     .setMessage("Permission required to save photos from the Web.")
  39.                     .setPositiveButton("Allow") { dialog, id ->
  40.                         ActivityCompat.requestPermissions(
  41.                             context,
  42.                             arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
  43.                             MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE
  44.                         )
  45.                         context.finish()
  46.                     }
  47.                     .setNegativeButton("Deny") { dialog, id -> dialog.cancel() }
  48.                     .show()
  49.             } else {
  50.                 // No explanation needed, we can request the permission.
  51.                 ActivityCompat.requestPermissions(
  52.                     context,
  53.                     arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
  54.                     MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE
  55.                 )
  56.                 // MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE is an
  57.                 // app-defined int constant. The callback method gets the
  58.                 // result of the request.
  59.  
  60.             }
  61.         } else {
  62.             // Permission has already been granted
  63.             downloadImage(imageUrl)
  64.         }
  65.     }
  66.  
  67.  
  68.     fun onRequestPermissionsResult(
  69.         requestCode: Int,
  70.         permissions: Array<String>,
  71.         grantResults: IntArray
  72.     ) {
  73.         when (requestCode) {
  74.             MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE -> {
  75.                 // If request is cancelled, the result arrays are empty.
  76.                 if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
  77.                     // permission was granted, yay!
  78.                     // Download the Image
  79.                     downloadImage(imageUrl)
  80.                 } else {
  81.                     // permission denied, boo! Disable the
  82.                     // functionality that depends on this permission.
  83.  
  84.                 }
  85.                 return
  86.             }
  87.             // Add other 'when' lines to check for other
  88.             // permissions this app might request.
  89.             else -> {
  90.                 // Ignore all other requests.
  91.             }
  92.         }
  93.     }
  94.  
  95.     private fun downloadImage(url: String) {
  96.         val directory = File(Environment.DIRECTORY_PICTURES)
  97.  
  98.         if (!directory.exists()) {
  99.             directory.mkdirs()
  100.         }
  101.  
  102.         val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
  103.  
  104.         val downloadUri = Uri.parse(url)
  105.  
  106.         val request = DownloadManager.Request(downloadUri).apply {
  107.             setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
  108.                 .setAllowedOverRoaming(false)
  109.                 .setTitle(url.substring(url.lastIndexOf("/") + 1))
  110.                 .setDescription("")
  111.                 .setDestinationInExternalPublicDir(
  112.                     directory.toString(),
  113.                     url.substring(url.lastIndexOf("/") + 1)
  114.                 )
  115.         }
  116.  
  117.         val downloadId = downloadManager.enqueue(request)
  118.         val query = DownloadManager.Query().setFilterById(downloadId)
  119.         Thread(Runnable {
  120.             var downloading = true
  121.             while (downloading) {
  122.                 val cursor: Cursor = downloadManager.query(query)
  123.                 cursor.moveToFirst()
  124.                 if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
  125.                     downloading = false
  126.                 }
  127.                 val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
  128.                 msg = statusMessage(url, directory, status)
  129.                 if (msg != lastMsg) {
  130.                     context.runOnUiThread {
  131.                         Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
  132.                     }
  133.                     lastMsg = msg ?: ""
  134.                 }
  135.                 cursor.close()
  136.             }
  137.         }).start()
  138.     }
  139.  
  140.     private fun statusMessage(url: String, directory: File, status: Int): String? {
  141.         var msg = ""
  142.         msg = when (status) {
  143.             DownloadManager.STATUS_FAILED -> "Download has been failed, please try again"
  144.             DownloadManager.STATUS_PAUSED -> "Paused"
  145.             DownloadManager.STATUS_PENDING -> "Pending"
  146.             DownloadManager.STATUS_RUNNING -> "Downloading..."
  147.             DownloadManager.STATUS_SUCCESSFUL -> "Image downloaded successfully in $directory" + File.separator + url.substring(
  148.                 url.lastIndexOf("/") + 1
  149.             )
  150.             else -> "There's nothing to download"
  151.         }
  152.         return msg
  153.     }
  154.  
  155.  
  156.     companion object {
  157.         private const val MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1
  158.     }
  159. }
RAW Paste Data