Last active
February 14, 2022 17:27
-
-
Save Shivamdhuria/0050da3b4c6e9a3560d98170ded6a986 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
val textview by lazy { findViewById<View>(R.id.textView) as TextView } | |
val progressBar by lazy { findViewById<View>(R.id.progressbar) as ProgressBar } | |
val buttonMusic by lazy { findViewById<View>(R.id.button_music) as Button } | |
var progressPercentage = 0 | |
private var job: Job? = null | |
val scope by lazy { CoroutineScope(Dispatchers.Main) } | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
Log.d("activity", "OnCreate") | |
buttonMusic.setOnClickListener { | |
startDownloading("Music", 200) | |
} | |
} | |
private fun startDownloading(item: String, delay: Long) { | |
job = scope.launch { | |
textview.text = "Downloading..." | |
delay(300) | |
while (progressPercentage != 100) { | |
delay(delay) | |
progressPercentage++ | |
textview.text = "Percentage...$progressPercentage" | |
progressBar.setProgress(progressPercentage) | |
logCoroutineInfo("$item | perc $progressPercentage") | |
} | |
textview.text = "$item Downloaded ✅" | |
} | |
} | |
fun logCoroutineInfo(msg: String) = println("Running on: [${Thread.currentThread().name}] | $msg") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment