Advertisement
laminaung

Untitled

Jun 27th, 2020
524
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 7.61 KB | None | 0 0
  1. package mm.basiceducation.beprimary.activity
  2.  
  3. import android.Manifest
  4. import android.app.DownloadManager
  5. import android.app.ProgressDialog
  6. import android.content.Context
  7. import android.content.Intent
  8. import android.content.pm.PackageManager
  9. import android.net.Uri
  10. import android.os.Bundle
  11. import android.os.Environment
  12. import android.view.View
  13. import android.widget.TextView
  14. import android.widget.Toast
  15. import androidx.appcompat.app.AppCompatActivity
  16. import androidx.core.app.ActivityCompat
  17. import androidx.core.content.ContextCompat
  18. import androidx.recyclerview.widget.RecyclerView
  19. import com.google.android.gms.ads.*
  20. import com.google.firebase.firestore.FirebaseFirestore
  21. import mm.basiceducation.beprimary.R
  22. import mm.basiceducation.beprimary.adapter.ChapterAdapter
  23. import mm.basiceducation.beprimary.dto.Chapter
  24. import mm.basiceducation.beprimary.listener.ClickListener
  25. import java.io.File
  26.  
  27. class ChapterActivity : AppCompatActivity() {
  28.  
  29.     lateinit var mAdView: AdView
  30.     private lateinit var mInterstitialAd: InterstitialAd
  31.  
  32.     companion object {
  33.         private const val REQUEST_CODE_PERMISSION_STORAGE = 100
  34.     }
  35.  
  36.     lateinit var grade: String
  37.     lateinit var subject: String
  38.  
  39.     override fun onCreate(savedInstanceState: Bundle?) {
  40.         super.onCreate(savedInstanceState)
  41.         setContentView(R.layout.activity_chapter)
  42.  
  43.         //request permission
  44.         if (!checkPermission()) {
  45.             requestPermission()
  46.         }
  47.  
  48.         val db = FirebaseFirestore.getInstance()
  49.         val data = mutableListOf<Chapter>()
  50.         val text = findViewById<TextView>(R.id.chapter_text)
  51.         val recyclerView = findViewById<RecyclerView>(R.id.chatper_recyclerview)
  52.  
  53.         //banner
  54.         MobileAds.initialize(this)
  55.         mAdView = findViewById(R.id.chapter_adview)
  56.         val adRequest = AdRequest.Builder().build()
  57.         mAdView.loadAd(adRequest)
  58.  
  59.         //interstitial
  60.         mInterstitialAd = InterstitialAd(this)
  61.         mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
  62.         mInterstitialAd.loadAd(AdRequest.Builder().build())
  63.  
  64.         grade = intent?.getStringExtra("grade") as String
  65.         val user = intent?.getStringExtra("user")
  66.         subject = intent?.getStringExtra("subject") as String
  67.  
  68.         supportActionBar?.title = "$grade $subject"
  69.  
  70.         db.collection("chapter")
  71.                 .whereEqualTo("subject_id", intent.getIntExtra("subjectid", 0))
  72.                 .get()
  73.                 .addOnCompleteListener { task ->
  74.                     if (task.isSuccessful) {
  75.                         for (document in task.result!!) {
  76.                             data.add(document.toObject(Chapter::class.java))
  77.                         }
  78.                         if (data.size < 1) {
  79.                             text.visibility = View.VISIBLE
  80.                         }
  81.                         data.sort()
  82.                         val adapter = ChapterAdapter(data, applicationContext)
  83.                         recyclerView.adapter = adapter
  84.                         adapter.setClickListener(ClickListener { _, positon ->
  85.  
  86.                             if (checkPermission()) {
  87.                                 downloadPDF(data[positon].link, "$grade $user $subject ${data[positon].description}.pdf")
  88.                             } else {
  89.                                 requestPermission()
  90.                                 Toast.makeText(applicationContext, "Need Permission", Toast.LENGTH_SHORT).show()
  91.                             }
  92.                         })
  93.                     }
  94.                 }
  95.     }
  96.  
  97.     fun downloadPDF(link: String, name: String) {
  98.  
  99.         // two hour to find this single line of code
  100.         val path = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), name)
  101.  
  102.         if (!path.exists()) {
  103.  
  104. //            Toast.makeText(applicationContext, path.toString(), Toast.LENGTH_SHORT).show()
  105.             val uri = Uri.parse(link)
  106.             val request = DownloadManager.Request(uri)
  107.             request.setTitle(name)
  108.             request.setDescription(name)
  109.             request.setVisibleInDownloadsUi(true)
  110.             request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
  111.             request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name)
  112.  
  113.             val downloadManager =
  114.                     getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
  115.             val downloadid = downloadManager.enqueue(request)
  116.  
  117.  
  118.             val progressBarDialog = ProgressDialog(this)
  119.             progressBarDialog.setTitle("Loading, Please Wait")
  120. //            progressBarDialog.setTitle(name)
  121.             progressBarDialog.setCancelable(false)
  122.             progressBarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
  123.             progressBarDialog.progress = 0
  124.  
  125.             Thread(Runnable {
  126.                 var downloading = true
  127.                 val manager =
  128.                         this.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
  129.                 while (downloading) {
  130.                     val q = DownloadManager.Query()
  131.                     q.setFilterById(downloadid) //filter by id which you have receieved when reqesting download from download manager
  132.                     val cursor = manager.query(q)
  133.                     cursor.moveToFirst()
  134.                     val bytesDownloaded = cursor.getInt(
  135.                             cursor
  136.                                     .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
  137.                     )
  138.                     val bytes_total =
  139.                             cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
  140.                     if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
  141.  
  142.                         progressBarDialog.dismiss()
  143.                         downloading = false
  144.  
  145.                     }
  146.                     val dl_progress = (bytesDownloaded * 100L / bytes_total).toInt()
  147.                     runOnUiThread { progressBarDialog.progress = dl_progress as Int }
  148.  
  149.                     // Log.d(Constants.MAIN_VIEW_ACTIVITY, statusMessage(cursor));
  150.                     cursor.close()
  151.                 }
  152.             }).start()
  153.  
  154.             progressBarDialog.show()
  155.  
  156.         } else {
  157.  
  158.             val intent = Intent(this, DetailActivity::class.java)
  159.             intent.putExtra("PDF", name)
  160.             intent.putExtra("name", "$grade $subject")
  161.  
  162.             if (mInterstitialAd.isLoaded) {
  163.                 mInterstitialAd.show()
  164.                 mInterstitialAd.adListener = object : AdListener() {
  165.                     override fun onAdClosed() {
  166.                         super.onAdClosed()
  167.                         mInterstitialAd.loadAd(AdRequest.Builder().build())
  168.                         startActivity(intent)
  169.                     }
  170.                 }
  171.             } else {
  172.                 startActivity(intent)
  173.             }
  174.         }
  175.  
  176.     }
  177.  
  178.  
  179.     private fun checkPermission(): Boolean {
  180.         return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
  181.     }
  182.  
  183.     private fun requestPermission() {
  184.         ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CODE_PERMISSION_STORAGE)
  185.     }
  186.  
  187.     override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
  188.         if (requestCode == REQUEST_CODE_PERMISSION_STORAGE) {
  189.             if (grantResults.isEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  190.  
  191.             } else if (grantResults.isEmpty() && grantResults[0] == PackageManager.PERMISSION_DENIED) {
  192.             }
  193.         }
  194.  
  195.     }
  196.  
  197. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement