RaptorDroid
07/01/2020, 9:52 AMclass UploadWorker(val context: Context, workerParams: WorkerParameters) : Worker(
context,
workerParams
) {
private val TAG = "UploadWorker"
override fun doWork(): Result {
return try {
val firebaseStorage = FirebaseStorage.getInstance()
val sharedPref = context.getSharedPreferences("image_sessions", Context.MODE_PRIVATE)
val imagePath = inputData.getString("image_path")
val imageURL = inputData.getString("image_url")
val imageId = inputData.getString("image_id")
val outputData = createOutputDate(imagePath)
val countLatch = CountDownLatch(1)
val imageFile = Uri.fromFile(File(imagePath!!))
val imageStorageRef = firebaseStorage.getReferenceFromUrl(imageURL!!)
var uploadTask = imageStorageRef.putFile(imageFile)
var isSaved = false
val sessionUri = sharedPref.getString(imageId, null)
if (sessionUri != null) {
isSaved = true
val uri = Uri.parse(sessionUri)
uploadTask =
imageStorageRef.putFile(imageFile, StorageMetadata.Builder().build(), uri)
}
uploadTask.addOnProgressListener { taskSnapshot ->
if (!isSaved) {
val uri = taskSnapshot.uploadSessionUri
with(sharedPref.edit()) {
putString(imageId, uri.toString())
commit()
}
}
val progress = (100.0 * taskSnapshot.bytesTransferred) / taskSnapshot.totalByteCount
Log.d(TAG, "FILE PROGRESS : $progress % ")
makeStatusNotification(progress.toInt())
}.addOnPausedListener {taskSnapshot->
val progress = (100.0 * taskSnapshot.bytesTransferred) / taskSnapshot.totalByteCount
Log.d(TAG, "File PAUSED!!!! $progress % ")
}.addOnSuccessListener {
with(sharedPref.edit()) {
remove(imageId)
commit()
}
countLatch.countDown()
}.addOnFailureListener {
countLatch.countDown()
}
try {
countLatch.await()
} catch (e: InterruptedException) {
e.printStackTrace()
}
deleteNotification()
Log.d(TAG, "doWork result value END HERE ")
Result.success(outputData)
} catch (e: Exception) {
Result.failure()
}
}
I am trying to create a worker that can upload image to firebase storage whenever there is any kind of network connection and if the constraints are not meant then continue uploading image from same place where it left last time I mean I don't want image to restart uploading from start but I think I have made some mistakes here .
As my app is able to upload image correctly but consumes lot of data I think it restarts the upload from start each time worker is stopped due to app kill or network issue.
For image of 1MB data consumption is 3-5MB if worker is stopped due to any reasons
Please help me here 🙏