Upload Files to Huawei Drive with WorkManager

Abdurrahim Çillioğlu
Huawei Developers
Published in
6 min readFeb 23, 2021

Hi everyone, In this article, we’ll explore how scheduling a task to upload files to the Huawei Drive with WorkManager. Also, we will develop a demo app using Kotlin in the Android Studio.

Huawei Drive Kit

Drive Kit (the short form of Huawei Drive Kit) allows developers to create apps that use Drive. Drive Kit gives us cloud storage capabilities for our apps, enabling users to store files that are created while using our apps, including photos, videos, and documents.

Some of the main function of the Drive kit:

  • Obtaining User Information
  • Managing and Searching for Files
  • Storing App Data
  • Performing Batch Operations

You can find more information in the official documentation link.

We’re not going to go into the details of adding Account Kit and Drive Kit to a project. You can follow the instructions to add Drive Kit to your project via official docs or codelab.

WorkManager

WorkManager is an API that makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or the device restarts. WorkManager gives us a guarantee that our action will be taken, regardless of if the app exits. But, our tasks can be deferrable to wait for some constraints to be met or to save battery life. We will go into details on WorkManager while developing the app.

Our Sample Project DriveWithWorkManager

In this project, we’re going to develop a sample app that uploading users’ files to their drive with WorkManager. Developers can use the users’ drive to save their photos, videos, documents, or app data. With the help of WorkManager, we ensure that our upload process continues even if our application is terminated.

Setup the Project

Add the necessary dependencies to build.gradle (app level)

Layout File

activity_main.xml is the only layout file in our project. There are two buttons here, one button for login with Huawei ID and one button for creating a work. I should note that apps that support Huawei ID sign-in must comply with the Huawei ID Sign-In Button Usage Rules. Also, we used the Drive icon here. But, the icon must comply with the HUAWEI Drive icon specifications. We can download and customize icons in compliance with the specifications. For more information about the specifications, click here.

Permission for Storage

We need permission to access the phone’s storage. Let’s add the necessary permissions to our manifest.

We have two code file in our application: MainActivity.kt and UploadWorker.kt

MainActivity

MainActivity.kt -> Drive functions strongly depend on Huawei Id. To use Drive functions, users must sign in with their Huawei IDs. In this file, we perform our login process and create new works.

Let’s interpret the functions on this page one by one.

onCreate() - Starting in API 23, we need to request the user for specific permission on runtime. So, we added a simple permission request. Then, we added our button-click listeners.
signIn() - We create a scope list and added the necessary drive permissions. Then, we started the login process. If you want to use other drive functions, ensure to add permission here.
refreshAt() - We can obtain a new accessToken through the HMS Core SDK.
checkDriveCode() - First, we checked whether the unionId and access token are null or an empty string. Then, we construct a DriveCredential.Builder object and returned the code.
onActivityResult() - We get the authorization result and obtain the authorization code from AuthAccount.
createWorkRequest() - I would like to explain this function after a quick explanation of the Work Request.

Creating Work Request

This is an important part of our application. With the creatingWorkRequest function, we create a work request. There are two types of work requests; OneTimeWorkRequest and PeriodicWorkRequest. OneTimeWorkRequest is run only once. We used it for simplicity in our example. PeriodicWorkRequest is used to run tasks that need to be called periodically until canceled.

createWorkRequest - We created an OneTimeWorkRequest and added input data as accessToken and unionId to the work. We would also like to make sure that our works only run in certain situations such as we have a network and not a low battery. So, we used constraints to achieve this. Finally, we enqueued our uploadWorkRequest to run.

UploadWorker

In time, WorkManager will run a worker. To define a worker, we should create a class that extends the Worker class. For Kotlin users, WorkManager provides first-class support for coroutines. So, we can extend our UploadWorker class from CoroutinesWorker. And, it takes two parameters; context and worker parameters.

Then, we need to override the doWork function. doWork is a suspending function, it means that we can run asynchronous tasks and perform network operations. Also, it handles stoppages and cancellations automatically.

Dispatchers.IO is optimized to perform network I/O outside of the main thread. So, we call the withContext(Dispatchers.IO) to create a block that runs on the IO thread pool.

To gets the accessToken and unionId as input data, we used inputData.getString. Then, we checked the drive status. If our access code is still valid, we can use it in the Drive Kit. Otherwise, we have to get renew our code to use Drive Kit.

createAndUploadFile() - First, we created a folder in the Drive named DriveWithWorkManager. We have already put a photo on Android/data/com.huawei.drivewithwork/files as you see in the below image. Note: Don’t forget to replace the package name with yours and put a sample image.
Then, we got the file path of the image on Android.

Now, everything is ready. We can upload our file to the Drive. Let’s run our app and see what happens.

Launch the app and login with your Huawei Id. Then click the Create A Work Button. After waiting at least a minute, WorkManager will run our work if the conditions are met. And our photo will be uploaded to the drive.

There are two ways to upload files: direct upload and resumable upload. We used the direct upload in our sample app. Direct upload allows a file of max. 20 MB and, resumable upload doesn’t have a limit. Direct upload is recommended for files smaller than 5 MB and resumable upload for files larger than 5 MB. You can also see the codes of resumable upload as the comment.

Tips & Tricks

  • Your app can save app data, such as configuration files and archives in the app folder inside Drive. This folder stores any files with which the user does not have direct interactions. Also, this folder can be accessed only by your app, and the content in the folder is hidden to the user and other apps using Drive.
  • If the size of the file you download or upload is big, you can use NetworkType.UNMETERED constraint to reduce the cost to the user.

Conclusion

In this article, we have learned how to use Drive Kit with WorkManager. And, we’ve developed a sample app that uploads images to users’ drives. In addition to uploading a file, Drive Kit offers many functions such as reading, writing, and syncing files in Huawei Drive. Please do not hesitate to ask your questions as a comment. You can also ask your questions via the Huawei Developer Forum.

Thank you for your time and dedication. I hope it was helpful. See you in other articles!

References

Huawei Drive Kit Official Documentation
Huawei Drive Kit Official Codelab
WorkManager Official Documentation

--

--