Skip to content

Commit

Permalink
Implement Downloading Logic with Pause Resume Support
Browse files Browse the repository at this point in the history
  • Loading branch information
gunishjain committed Nov 12, 2024
1 parent dec6e5f commit 24cc7c4
Show file tree
Hide file tree
Showing 14 changed files with 361 additions and 54 deletions.
8 changes: 7 additions & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ plugins {

android {
namespace = "com.gunishjain.sample"
compileSdk = 34
compileSdk = 35

defaultConfig {
applicationId = "com.gunishjain.sample"
Expand Down Expand Up @@ -41,6 +41,8 @@ android {

dependencies {

implementation(project(":grabbit"))

implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
Expand All @@ -56,4 +58,8 @@ dependencies {
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)




}
4 changes: 4 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
android:name=".MyApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
Expand Down
131 changes: 107 additions & 24 deletions app/src/main/java/com/gunishjain/sample/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,127 @@ import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Button
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.*
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.gunishjain.sample.ui.theme.GrabbitTheme
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
GrabbitTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Greeting(
name = "Android",
modifier = Modifier.padding(innerPadding)
)
}
}
DownloadUI()
}
}
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
fun DownloadUI() {
val context = LocalContext.current
val grabbit = (context.applicationContext as MyApplication).grabbit

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
GrabbitTheme {
Greeting("Android")
var downloadProgress by remember { mutableIntStateOf(0) }
var isDownloading by remember { mutableStateOf(false) }
var isPaused by remember { mutableStateOf(false) }
var downloadId by remember { mutableIntStateOf(-1) }

// Start download
fun startDownload(url: String, dirPath: String, fileName: String) {
val request = grabbit.newRequest(url, dirPath, fileName).build()

downloadId = grabbit.enqueue(
request,
onStart = {
isDownloading = true
isPaused = false
},
onProgress = { progress ->
downloadProgress = progress
},
onPause = {
isPaused = true
},
onCompleted = {
isDownloading = false
},
onError = { error ->
// Handle error (optional)
}
)
}

// Pause download
fun pauseDownload() {
grabbit.pause(downloadId)
}

// Resume download
fun resumeDownload() {
grabbit.resume(downloadId)
}

// Cancel download
fun cancelDownload() {
grabbit.cancel(downloadId)
isDownloading = false
downloadProgress = 0
}
}

Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
// Progress bar
Text("Download Progress: $downloadProgress%")
LinearProgressIndicator(
progress = downloadProgress / 100f,
modifier = Modifier.fillMaxWidth().padding(top = 16.dp)
)

Spacer(modifier = Modifier.height(32.dp))

// Buttons for control
if (isDownloading) {
if (isPaused) {
Button(onClick = { resumeDownload() }) {
Text("Resume")
}
} else {
Button(onClick = { pauseDownload() }) {
Text("Pause")
}
}
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = { cancelDownload() }) {
Text("Cancel")
}
} else {
Button(onClick = {
startDownload(
url = "https://www.learningcontainer.com/download/sample-50-mb-pdf-file/?wpdmdl=3675&refresh=6721f942bd70b1730279746",
dirPath = "/downloads",
fileName = "gunish.pdf"
)
}) {
Text("Download")
}
}
}
}

15 changes: 15 additions & 0 deletions app/src/main/java/com/gunishjain/sample/MyApplication.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.gunishjain.sample

import android.app.Application
import com.gunishjain.grabbit.Grabbit

class MyApplication : Application() {

lateinit var grabbit: Grabbit

override fun onCreate() {
super.onCreate()
grabbit = Grabbit.create()
}

}
3 changes: 3 additions & 0 deletions grabbit/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,7 @@ dependencies {
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)

implementation(libs.retrofit)
implementation(libs.okhttp)
}
18 changes: 10 additions & 8 deletions grabbit/src/main/java/com/gunishjain/grabbit/Grabbit.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.gunishjain.grabbit

import com.gunishjain.grabbit.internal.download.DownloadDispatcher
import com.gunishjain.grabbit.internal.download.DownloadRequest
import com.gunishjain.grabbit.internal.download.DownloadRequestQueue

class Grabbit private constructor(private val config: DownloadConfig){

Expand All @@ -17,7 +19,7 @@ class Grabbit private constructor(private val config: DownloadConfig){

}

//Need to create Req Queue and add requests to it with callbacks
private val requestQueue = DownloadRequestQueue(DownloadDispatcher(config.httpClient))

fun enqueue(
request: DownloadRequest,
Expand All @@ -26,34 +28,34 @@ class Grabbit private constructor(private val config: DownloadConfig){
onPause: () -> Unit= {},
onCompleted: () -> Unit = {},
onError: (error: String) -> Unit = {_->}
) {
) : Int {
request.onStart = onStart
request.onProgress = onProgress
request.onPause = onPause
request.onCompleted = onCompleted
request.onError = onError

//Add request to queue
return requestQueue.enqueue(request)

}
fun pause(id: Int){

requestQueue.pause(id)
}

fun resume(id: Int){

requestQueue.resume(id)
}

fun cancel(id: Int){

requestQueue.cancel(id)
}

fun cancel(tag: String){

requestQueue.cancel(tag)
}

fun cancelAll(){

requestQueue.cancelAll()
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import kotlinx.coroutines.launch
class DownloadDispatcher(private val httpClient: HttpClient) {

private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private val downloadTasks = mutableMapOf<Int, DownloadTask>()

private fun executeOnMain(block: () -> Unit){
scope.launch {
Expand All @@ -18,6 +19,10 @@ class DownloadDispatcher(private val httpClient: HttpClient) {
}

fun enqueue(req: DownloadRequest) : Int {

val downloadTask = DownloadTask(req,httpClient)
downloadTasks[req.downloadId] = downloadTask

val job = scope.launch {
execute(req)
}
Expand All @@ -38,15 +43,28 @@ class DownloadDispatcher(private val httpClient: HttpClient) {
executeOnMain { request.onPause() }
},
onCompleted = {
executeOnMain { request.onCompleted() }
executeOnMain {
request.onCompleted()
}
downloadTasks.remove(request.downloadId)

},
onError = {
executeOnMain { request.onError(it) }
downloadTasks.remove(request.downloadId)
}
)

}

fun pause(downloadId: Int) {
downloadTasks[downloadId]?.pauseDownload()
}

fun resume(downloadId: Int) {
downloadTasks[downloadId]?.resumeDownload()
}

fun cancel(req: DownloadRequest) {
req.job.cancel()
}
Expand All @@ -56,5 +74,4 @@ class DownloadDispatcher(private val httpClient: HttpClient) {
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class DownloadRequest private constructor(

internal var totalBytes: Long = 0
internal var downloadedBytes: Long = 0
internal lateinit var job: Job //using lateintit since we are not initializing it here
internal lateinit var job: Job //using lateintit since we are not initializing it here
internal lateinit var onStart: () -> Unit
internal lateinit var onProgress: (value: Int) -> Unit
internal lateinit var onPause: () -> Unit
Expand Down Expand Up @@ -57,7 +57,7 @@ class DownloadRequest private constructor(
tag = tag,
dirPath = dirPath,
fileName = fileName,
downloadId = getUniqueDownloadId(),
downloadId = getUniqueDownloadId(url, dirPath, fileName),
readTimeout = readTimeOut,
connectTimeout = connectTimeOut
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,17 @@ class DownloadRequestQueue(private val dispatcher: DownloadDispatcher) {
fun enqueue(request: DownloadRequest) :Int {

idRequestMap[request.downloadId] = request

return dispatcher.enqueue(request)

}

fun pause(id: Int) {



dispatcher.pause(id)
}

fun resume(id: Int) {

dispatcher.resume(id)
}

fun cancel(id: Int) {
Expand Down Expand Up @@ -48,7 +47,4 @@ class DownloadRequestQueue(private val dispatcher: DownloadDispatcher) {

}




}
Loading

0 comments on commit 24cc7c4

Please sign in to comment.