Downloading Huawei Drive Files with Network Kit - Huawei Developers

The new Huawei Network kit provides you with convenient and easy to use APIs to perform HTTP operations. You can use it as HTTP Client to quickly download many kind of files from internet. In this article we are going to use it to download files from Huawei Drive by using the Public APIs, by this way we will be able to browse and download files, even from non-huawei devices.
Note: This article is a continuation of my previous post called "Accessing to Huawei Drive by using AppAuth and REST APIs". Is highly recommended to read it first before continue with this one.
Integrating Drive Kit
We will use the new Huawei Drive kit to download the user's files stored in Huawei Drive, by doing so, the kit will handle the HTTP calls in asynchronous mode for us. Add the Network Kit SDK under dependencies in your app-level build.gradle. We will also use CardView to display the user's files in a list, so let us add both dependencies.
Code:
implementation 'com.huawei.hms:network-embedded:5.0.1.301'
implementation "androidx.cardview:cardview:1.0.0"
Network Kit must be initialized before calling it's APIs, we can ensure the initialization upon each startup by defining our own Application class.
MyApplication.kt
Code:
class MyApplication : Application(){
override fun onCreate() {
super.onCreate()
initNetworkKit()
}
fun initNetworkKit() {
// Initialize the object only once, upon the first call.
NetworkKit.init(this, object : NetworkKit.Callback() {
override fun onResult(result: Boolean) {
val TAG = "NetworkKit"
if (result) {
Log.i(TAG, "Networkkit init success")
} else {
Log.i(TAG, "Networkkit init failed")
}
}
})
}
}
Do not forget to register your Application class in your AndroidManifest.xml
AndroidManifest.xml (Modifying)
Code:
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppAuthDriveKit">
Modifying the Contract
Let us add the file management related methods to our abstract class, this will be useful if we want to add more Drive providers in the future (like Microsoft's OneDrive).
DriveService.kt (Modifying)
Code:
abstract class DriveService (val service: AuthorizationService,
val authState: AuthState){
var driveListener:OnDriveEventListener?=null
abstract fun startService()
abstract fun listFiles()
abstract fun downloadFile(context: Context, cloudFile: CloudFile)
abstract fun uploadFile(file: File)
interface OnDriveEventListener{
fun onServiceReady(storageData: String)
fun onServiceFailure(info: String)
fun onFilesListed(files: List<CloudFile>)
fun onFileUploaded()
fun onDownloadStarted(cloudFile: CloudFile)
fun onDownloadProgress(cloudFile: CloudFile, progress: Int)
fun onFileDownloaded(cloudFile: CloudFile)
}
}
Listing the Files
We will call the Files.List API to get the details of all the stored user's files on his Root directory. First, we need a class to store all the information of a file in the cloud. A data class will be useful to achieve this.
Note: A file object in the cloud has a lot of information, for demonstration purposes we will just keep the most important properties.
Code:
data class CloudFile(
val filename: String,
val fileSuffix: String,
val createdTime: String,
val downloadLink: String,
val mimeType:String,
val fileSize:Int
){
val stringSizeInKb="${fileSize/1024} KB"
}
Previously, we have called he About API to get some general information about the user's Drive, into that information, it came the "domain", that's the name of the host which is able to dispatch all the Drive requests related to the current user. We will use the "domain" to query the file list. This information will be obtained by using a normal HTTP call.
Note: The next code can be improved by using the REST Client mode of Network Kit, but is not the focus of this article.
HuaweiDriveService.kt (modifying)
Code:
override fun listFiles() {
CoroutineScope(Dispatchers.IO).launch {
authState.performActionWithFreshTokens(service){accessToken,_,_->
val url="$domain/drive/v1/files?fields=*"
val conn=URL(url).openConnection() as HttpURLConnection
conn.addRequestProperty("Authorization","Bearer $accessToken")
conn.addRequestProperty("Cache-Control","no-cache")
val response=if(conn.responseCode<400) convertStreamToString(conn.inputStream)
else convertStreamToString(conn.errorStream)
if(conn.responseCode==200){
val json=JSONObject(response)
buildList(json)
}else driveListener?.onServiceFailure(response)
}
}
}
As you can see, the registered OnDriveEventListener will receive the list of available files in the Cloud. In this case, the DriveViewModel, which will store the files list into a MutableLiveData.
DriveViewModel.kt(Modifying)
Code:
var list=MutableLiveData<ArrayList<CloudFile>>()
override fun onFilesListed(files: List<CloudFile>) {
list.apply {
value?.run {
clear()
addAll(files)
}
postValue(value)
}
}
Let us define the view which will be used to display our file items.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
file_item.xml
XML:
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto">
<data class="FileItemBinding"
><variable
name="item"
type="com.hms.demo.appauthdrivekit.CloudFile" /></data>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
card_view:cardElevation="20dp"
card_view:cardCornerRadius="15dp"
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:padding="5dp"
android:layout_height="wrap_content"
>
<ImageView
android:id="@+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="@drawable/ic_insert_drive_file_black_18dp"
android:src="@drawable/ic_insert_drive_file_black_18dp"
android:layout_marginEnd="5dp"/>
<TextView
android:id="@+id/fileName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:text="@{item.filename}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/icon"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/fileType"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="@{item.fileSuffix}"
app:layout_constraintBottom_toTopOf="@+id/fileSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="@+id/icon"
app:layout_constraintTop_toBottomOf="@+id/fileName" />
<TextView
android:id="@+id/fileSize"
android:layout_width="0dp"
android:layout_height="19dp"
android:layout_marginStart="5dp"
android:layout_marginBottom="5dp"
android:text="@{item.stringSizeInKb}"
android:textAlignment="textEnd"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/icon" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</layout>
Is time to create the adapter, a download request will be triggered if the user performs a long click on any item.
FileAdapter.kt
Code:
class FileAdapter : RecyclerView.Adapter<FileAdapter.FileVH>() {
lateinit var items:ArrayList<CloudFile>
var cloudFileEventListener:CloudFileEventListener?=null
class FileVH(private val binding: FileItemBinding): RecyclerView.ViewHolder(binding.root),View.OnLongClickListener {
var fileEventListener:CloudFileEventListener?=null
fun bind(item:CloudFile){
binding.item=item
binding.root.setOnLongClickListener(this)
}
override fun onLongClick(v: View?): Boolean {
binding.item?.let {
fileEventListener?.onDownloadRequest(it)
}
return true
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileVH {
val layoutInflater=LayoutInflater.from(parent.context)
val binding=FileItemBinding.inflate(layoutInflater,parent,false)
return FileVH(binding).apply { fileEventListener= cloudFileEventListener}
}
override fun onBindViewHolder(holder: FileVH, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int {
return items.size
}
interface CloudFileEventListener{
fun onDownloadRequest(item:CloudFile)
}
}
Downloading a file
Before performing any File operation, we must make sure to have the related permissions granted, by othe way we will fall in a SecurityException. the DriveViewModel will listen for the download requests from the Recycler Adapter, and this Viewmodel is connected to our activity by the DriveNavigator interface, by using that connections, we can ask to the activity to check if the storage permissions are granted upon any download request.
DriveVM.kt (Modifying)
Code:
override fun onDownloadRequest(item:CloudFile) {
navigator?.apply {
if(checkStoragePermissions()){
val context=navigator as Context
driveService?.downloadFile(context,item)
} else requestStoragePermissions()
}
}
From the DriveActivity, we must check if the permissions are granted and asking for them if not.
DriveActivity.kt (Modifying)
Code:
override fun checkStoragePermissions(): Boolean {
val read=ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)
val write=ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
return read==PackageManager.PERMISSION_GRANTED&&write==PackageManager.PERMISSION_GRANTED
}
override fun requestStoragePermissions() {
val permissions= arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE)
requestPermissions(permissions, STORAGE_PERMISSIONS)
}
Since Android 10, the access to the user's storage must be performed by using MediaStore. As the file creation process is the same no matter the Drive provider (Huawei, Microsoft, Google, etc.), let's add to our DriveService class the capability of creating new Files, so any subclass of this will be able to create new files in the local storage.
DriveService.kt (Modifying)
Code:
open fun createFileUri(context: Context, item: CloudFile):Uri?{
val resolver=context.contentResolver
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, item.filename)
put(MediaStore.MediaColumns.MIME_TYPE, item.mimeType)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
put(MediaStore.MediaColumns.RELATIVE_PATH, "Documents")
}
}
return resolver.insert(MediaStore.Files.getContentUri("external"), contentValues)
}
Is time to download the file, at this point you may think we can easily download files by using the Network Kit file downloading capability. The problem here is the files.get web API of Drive Kit, doesn't provide you a file by definition, it provides only the file content and we must use that content as well as the file metadata to build the file by ourselves.
Let's suppose the APIs from other Drive providers have the same behavior (provide only the file content), in that case, we can add the download capability to the DriveService class. to achieve our goal, we must create an HTTP Client and a request.
DriveService.kt (Modifying)
Code:
private val httpClient:HttpClient by lazy { HttpClient.Builder()
.connectTimeout(10000)
.build() }
open fun buildGetRequest(url: String, headers: Map<String, String>):Request{
return httpClient.newRequest().apply {
url(url)
method("GET")
for(key in headers.keys){
addHeader(key,headers[key])
}
}.build()
}
Now we are ready to develop the file downloading capability.
DrveService.kt (Modifying)
Code:
open fun enqueueDownload(output:OutputStream,cloudFile: CloudFile, request: Request) {
httpClient.newSubmit(request).enqueue(object : Callback<ResponseBody?>() {
@Throws(IOException::class)
override fun onResponse(
submit: Submit<ResponseBody?>?,
response: Response<ResponseBody?>
) {
if(response.isOK){
driveListener?.onDownloadStarted(cloudFile)
response.body?.inputStream?.let {input->
val fileWriter= DataOutputStream(output)
val bytes=ByteArray(1024)
var downloaded=0
var readed=0
while (input.read(bytes,0,bytes.size).also { readed=it }>0){
downloaded+=readed
fileWriter.apply {
write(bytes,0,readed)
flush()
val progress=(downloaded*100)/cloudFile.fileSize
driveListener?.onDownloadProgress(cloudFile,progress)
}
}
fileWriter.close()
driveListener?.onFileDownloaded(cloudFile)
}
}
}
override fun onFailure(submit: Submit<ResponseBody?>?, throwable: Throwable) {
// Process the exception if the request fails.
Log.w("Download", "response onFailure = " + throwable.message)
}
})
}
As you can see, we are using the OnDriveEventListener interface to notify the download state and the download progress. Is time to override the downloadFile function in our HuaweiDriveService class.
HuaweiDriveService.kt (Modifying)
Code:
override fun downloadFile(context: Context, cloudFile: CloudFile) {
authState.performActionWithFreshTokens(service){ accessToken, _, _->
//Creating the file in the local storage
createFileUri(context,cloudFile)?.let {
val output=context.contentResolver.openOutputStream(it)
//Adding the authorization information for the request
val headers= mapOf("Content-Type" to "application/json","Authorization" to "Bearer $accessToken")
//Building the request
val request=buildGetRequest(cloudFile.downloadLink,headers)
//Starting the download
output?.let { stream -> enqueueDownload(stream,cloudFile,request) }
}
}
}
Starting and listening the download
Let's go back to the DriveVM class, from here, if a download request is received and the proper permissions are granted, it will call the driveService.downloadFile function to start the download task. The ViewModel will be notified about the download status changes thorugh the DriveService.OnDriveEventListener interface.
DriveVM.kt (Modifying)
Code:
override fun onDownloadStarted(cloudFile: CloudFile) {
Log.i("File","onDownloadStarted ${cloudFile.filename}")
}
override fun onDownloadProgress(cloudFile: CloudFile, progress: Int) {
navigator?.onDownloadProgress(cloudFile,progress)
}
override fun onFileDownloaded(cloudFile: CloudFile) {
navigator?.onFileDownloaded(cloudFile)
}
From this callbacks we will notify the activity (DriveNavigator) to update the user interface upon any download update.
DriveActivity.kt (Modifying)
Code:
private var progressDialog:AlertDialog?=null
override fun onDownloadProgress(cloudFile: CloudFile, progress: Int) {
runOnUiThread{
if(progressDialog==null) setupDialog(cloudFile.filename)
progressDialog?.apply {
setMessage("Progress: ${progress}% of ${cloudFile.fileSize/1000}KB")
show()
}
}
}
override fun onFileDownloaded(cloudFile: CloudFile) {
runOnUiThread {
progressDialog?.let {
if(it.isShowing) it.dismiss()
it.cancel()
}
progressDialog=null
AlertDialog.Builder(this)
.setTitle("Download Complete")
.setMessage("File ${cloudFile.filename} downloaded successfully!")
.setPositiveButton("Ok"){dialogInterface,_->
dialogInterface.dismiss()
}
.create().show()
}
}
private fun setupDialog(filename:String) {
progressDialog=AlertDialog.Builder(this).setTitle("Downloading: $filename").setCancelable(false).create()
}
Final Result
Conclusion
We have used Network Kit to download files from Huawei Drive without depending on the HMSCore APK, by this way, our app will be able to work even in non-Huawei Devices.
Network kit provides powerful APIs as it's File Upload/Download feature or it's REST Client mode, but is also useful to perform lower-level operations if is used in HttpClient mode, this versatility can help you to build any HTTP operation from your app with support for QUIC and Asynchronous mode.
Reference
Network Kit: URL Request
Drive Kit: Files.get
Original Source

Related

Building a news app using the QUIC protocol [Kotlin]

More information like this, you can visit HUAWEI Developer Forum​
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202352465220930189&fid=0101187876626530001
QUIC is a new transport protocol based on UDP wich allows improve the speed of the network connecctions due to the low latency of UDP. QUIC means Quick UDP Internet Connections and is planned to become a standar.
The key features of QUIC are:
Dramatically reduced connection establishment time
Improved congestion control
Multiplexing without head of line blocking
Connection migration
Some companies are starting supporting QUIC on their servers, now from the client side, is time to be prepared and adding QUIC support to our apps. This time we will buid a News App with QUIC support using the HQUIC kit.
HQUIC allow us connect with web services over the QUIC protocol, if the remote does not supports QUIC, the kit will use HTTP 2 instead automatically.
Previous Requirements
An android studio project
A developer account on newsapi.org
Adding the required dependencies
This example will require the next dependencies:
RecyclerView: To show all the news in a list.
SwipeRefreshLayout: To allw the user refreshing the screen using a swipe gesture.
HQUIC: The kit which allow us connect with services over QUIC
To use HQUIC you must add the Huawei's repository to your top level build.gradle.
Code:
buildscript {
buildscript {
repositories {
maven { url 'https://developer.huawei.com/repo/' }// This line
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
}
}
}
allprojects {
repositories {
maven { url 'https://developer.huawei.com/repo/' }// and this one
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Now add the required dependencies to your app level build.gradle
Code:
implementation 'com.huawei.hms:hquic-provider:5.0.0.300'
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
Designing the UI
We will show a list of items inside a RecyclerView, so you must design the item layout which will be displayed for each article. This basic view will only display the title, a brief introduction and the date of publication:
Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/content"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Content"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/title" />
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/content" />
</androidx.constraintlayout.widget.ConstraintLayout>
For the Activity Layout, the design will contain a SwipeRefresLayout with the RecyclerView inside
Code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/swipeRefreshLayout">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerNews"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</FrameLayout>
To show the articles on a recycler view you will need an adapter, the adapter will report the click event of any item to the given listener.
Code:
class NewsAdapter(val news:ArrayList<Article>,var listener: NewsViewHolder.onNewsClickListener?): RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() {
class NewsViewHolder(itemView: View, var listener:onNewsClickListener?) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
public fun init(article: Article){
itemView.title.text=article.title
itemView.content.text=article.description
val date= SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault()).parse(article.time)
itemView.time.text=date?.toString()
itemView.setOnClickListener(this)
}
interface onNewsClickListener{
fun onClickedArticle(position: Int)
}
override fun onClick(v: View?) {
listener?.onClickedArticle(adapterPosition)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val view=LayoutInflater.from(parent.context)
.inflate(R.layout.item_view,parent,false)
return NewsViewHolder(view,listener)
}
override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
holder.init(news[position])
}
override fun getItemCount(): Int {
return news.size
}
}
HQUIC Service
We will use the HQUICService class provided by the HQUIC demo project. This class abstracts the HQUIC kit capabilities and allows us to perform a request easily.
Code:
class HQUICService (val context: Context){
private val TAG = "HQUICService"
private val DEFAULT_PORT = 443
private val DEFAULT_ALTERNATEPORT = 443
private val executor: Executor = Executors.newSingleThreadExecutor()
private var cronetEngine: CronetEngine? = null
private var callback: UrlRequest.Callback? = null
/**
* Asynchronous initialization.
*/
init {
HQUICManager.asyncInit(
context,
object : HQUICManager.HQUICInitCallback {
override fun onSuccess() {
Log.i(TAG, "HQUICManager asyncInit success")
}
override fun onFail(e: Exception?) {
Log.w(TAG, "HQUICManager asyncInit fail")
}
})
}
/**
* Create a Cronet engine.
*
* @param url URL.
* @return cronetEngine Cronet engine.
*/
private fun createCronetEngine(url: String): CronetEngine? {
if (cronetEngine != null) {
return cronetEngine
}
val builder= CronetEngine.Builder(context)
builder.enableQuic(true)
builder.addQuicHint(getHost(url), DEFAULT_PORT, DEFAULT_ALTERNATEPORT)
cronetEngine = builder.build()
return cronetEngine
}
/**
* Construct a request
*
* @param url Request URL.
* @param method method Method type.
* @return UrlRequest urlrequest instance.
*/
private fun builRequest(url: String, method: String): UrlRequest? {
val cronetEngine: CronetEngine? = createCronetEngine(url)
val requestBuilder= cronetEngine?.newUrlRequestBuilder(url, callback, executor)
requestBuilder?.apply {
setHttpMethod(method)
return build()
}
return null
}
/**
* Send a request to the URL.
*
* @param url Request URL.
* @param method Request method type.
*/
fun sendRequest(url: String, method: String) {
Log.i(TAG, "callURL: url is " + url + "and method is " + method)
val urlRequest: UrlRequest? = builRequest(url, method)
urlRequest?.apply { urlRequest.start() }
}
/**
* Parse the domain name to obtain the host name.
*
* @param url Request URL.
* @return host Host name.
*/
private fun getHost(url: String): String? {
var host: String? = null
try {
val url1 = URL(url)
host = url1.host
} catch (e: MalformedURLException) {
Log.e(TAG, "getHost: ", e)
}
return host
}
fun setCallback(mCallback: UrlRequest.Callback?) {
callback = mCallback
}
}
Downloading the news
We will define a helper class to handle the request and parses the response into an ArrayList. The HQUIC kit will read certain number of bytes per time, for big responses the onReadCompleted method will be called more than once.
Code:
data class Article(val author:String,
val title:String,
val description:String,
val url:String,
val time:String)
class NewsClient(context: Context): UrlRequest.Callback() {
var hquicService: HQUICService? = null
val CAPACITY = 10240
val TAG="NewsDownloader"
var response:StringBuilder=java.lang.StringBuilder()
var listener:NewsClientListener?=null
init {
hquicService = HQUICService(context)
hquicService?.setCallback(this)
}
fun getNews(url: String, method:String){
hquicService?.sendRequest(url,method)
}
override fun onRedirectReceived(
request: UrlRequest,
info: UrlResponseInfo,
newLocationUrl: String
) {
request.followRedirect()
}
override fun onResponseStarted(request: UrlRequest, info: UrlResponseInfo) {
Log.i(TAG, "onResponseStarted: ")
val byteBuffer = ByteBuffer.allocateDirect(CAPACITY)
request.read(byteBuffer)
}
override fun onReadCompleted(
request: UrlRequest,
info: UrlResponseInfo,
byteBuffer: ByteBuffer
) {
Log.i(TAG, "onReadCompleted: method is called")
val readed=String(byteBuffer.array(), byteBuffer.arrayOffset(), byteBuffer.position())
response.append(readed)
request.read(ByteBuffer.allocateDirect(CAPACITY))
}
override fun onSucceeded(request: UrlRequest?, info: UrlResponseInfo?) {
//If everything is ok you can read the response body
val json=JSONObject(response.toString())
val array=json.getJSONArray("articles")
val list=ArrayList<Article>()
for (i in 0 until array.length()){
val article=array.getJSONObject(i)
val author=article.getString("author")
val title=article.getString("title")
val description=article.getString("description")
val time=article.getString("publishedAt")
val url=article.getString("url")
list.add(Article(author, title, description, url, time))
}
listener?.onSuccess(list)
}
override fun onFailed(request: UrlRequest, info: UrlResponseInfo, error: CronetException) {
//If someting fails you must report the error
listener?.onFailure(error.toString())
}
public interface NewsClientListener{
fun onSuccess(news:ArrayList<Article>)
fun onFailure(error: String)
}
}
Making the request
Define tue request properties
Code:
private val API_KEY="YOUR_API_KEY"
private val URL = "https://newsapi.org/v2/top-headlines?apiKey=$API_KEY"
private val METHOD = "GET"
Call the getNews function to start the request, if everything goes well, the list of news will be delivered on the onSuccess callback. If an error ocurs, the onFailure callback will be triggered.
Code:
private fun getNews() {
val country=Locale.getDefault().country
val url= "$URL&country=$country"
Log.e("URL",url)
val downloader=NewsClient(this)
downloader.apply {
[email protected]
getNews(url,METHOD)
}
}
override fun onSuccess(news: ArrayList<Article>) {
this.news.apply {
clear()
addAll(news)
}
runOnUiThread{
swipeRefreshLayout.isRefreshing=false
loadingDialog?.dismiss()
adapter?.notifyDataSetChanged()
}
}
override fun onFailure(error: String) {
val errorDialog=AlertDialog.Builder(this).apply {
setTitle(R.string.error_title)
val message="${getString(R.string.error_message)} \n $error"
setMessage(message)
setPositiveButton(R.string.ok){ dialog, _ ->
dialog.dismiss()
}
setCancelable(false)
create()
show()
}
}
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Conclusion
Is just a question of time for the QUIC protocol to become in the new standard of internet connections. For now you can get your apps ready to suppot it and provide the best user experience.
Test this demo: https://github.com/danms07/HQUICNews
Reference
Official Document
HQUIC sample code
what is it difference between QUIC and retrofit ?

Building a news app using the QUIC protocol [Kotlin]

QUIC is a new transport protocol based on UDP wich allows improve the speed of the network connecctions due to the low latency of UDP. QUIC means Quick UDP Internet Connections and is planned to become a standar.
The key features of QUIC are:
Dramatically reduced connection establishment time
Improved congestion control
Multiplexing without head of line blocking
Connection migration
Some companies are starting supporting QUIC on their servers, now from the client side, is time to be prepared and adding QUIC support to our apps. This time we will buid a News App with QUIC support using the HQUIC kit.
HQUIC allow us connect with web services over the QUIC protocol, if the remote does not supports QUIC, the kit will use HTTP 2 instead automatically.
Previous Requirements
An android studio project
A developer account on newsapi.org
Adding the required dependencies
This example will require the next dependencies:
RecyclerView: To show all the news in a list.
SwipeRefreshLayout: To allw the user refreshing the screen using a swipe gesture.=
HQUIC: The kit which allow us connect with services over QUIC
To use HQUIC you must add the Huawei's repository to your top level build.gradle.
Code:
buildscript {
buildscript {
repositories {
maven { url 'https://developer.huawei.com/repo/' }// This line
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
}
}
}
allprojects {
repositories {
maven { url 'https://developer.huawei.com/repo/' }// and this one
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Now add the required dependencies to your app level build.gradle
Code:
implementation 'com.huawei.hms:hquic-provider:5.0.0.300'
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
Designing the UI
We will show a list of items inside a RecyclerView, so you must design the item layout which will be displayed for each article. This basic view will only display the title, a brief introduction and the date of publication:
Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/content"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Content"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/title" />
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/content" />
</androidx.constraintlayout.widget.ConstraintLayout>
For the Activity Layout, the design will contain a SwipeRefresLayout with the RecyclerView inside
Code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/swipeRefreshLayout">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerNews"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</FrameLayout>
To show the articles on a recycler view you will need an adapter, the adapter will report the click event of any item to the given listener.
Code:
class NewsAdapter(val news:ArrayList<Article>,var listener: NewsViewHolder.onNewsClickListener?): RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() {
class NewsViewHolder(itemView: View, var listener:onNewsClickListener?) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
public fun init(article: Article){
itemView.title.text=article.title
itemView.content.text=article.description
val date= SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault()).parse(article.time)
itemView.time.text=date?.toString()
itemView.setOnClickListener(this)
}
interface onNewsClickListener{
fun onClickedArticle(position: Int)
}
override fun onClick(v: View?) {
listener?.onClickedArticle(adapterPosition)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val view=LayoutInflater.from(parent.context)
.inflate(R.layout.item_view,parent,false)
return NewsViewHolder(view,listener)
}
override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
holder.init(news[position])
}
override fun getItemCount(): Int {
return news.size
}
}
HQUIC Service
We will use the HQUICService class provided by the HQUIC demo project. This class abstracts the HQUIC kit capabilities and allows us to perform a request easily.
Code:
class HQUICService (val context: Context){
private val TAG = "HQUICService"
private val DEFAULT_PORT = 443
private val DEFAULT_ALTERNATEPORT = 443
private val executor: Executor = Executors.newSingleThreadExecutor()
private var cronetEngine: CronetEngine? = null
private var callback: UrlRequest.Callback? = null
/**
* Asynchronous initialization.
*/
init {
HQUICManager.asyncInit(
context,
object : HQUICManager.HQUICInitCallback {
override fun onSuccess() {
Log.i(TAG, "HQUICManager asyncInit success")
}
override fun onFail(e: Exception?) {
Log.w(TAG, "HQUICManager asyncInit fail")
}
})
}
/**
* Create a Cronet engine.
*
* @param url URL.
* @return cronetEngine Cronet engine.
*/
private fun createCronetEngine(url: String): CronetEngine? {
if (cronetEngine != null) {
return cronetEngine
}
val builder= CronetEngine.Builder(context)
builder.enableQuic(true)
builder.addQuicHint(getHost(url), DEFAULT_PORT, DEFAULT_ALTERNATEPORT)
cronetEngine = builder.build()
return cronetEngine
}
/**
* Construct a request
*
* @param url Request URL.
* @param method method Method type.
* @return UrlRequest urlrequest instance.
*/
private fun builRequest(url: String, method: String): UrlRequest? {
val cronetEngine: CronetEngine? = createCronetEngine(url)
val requestBuilder= cronetEngine?.newUrlRequestBuilder(url, callback, executor)
requestBuilder?.apply {
setHttpMethod(method)
return build()
}
return null
}
/**
* Send a request to the URL.
*
* @param url Request URL.
* @param method Request method type.
*/
fun sendRequest(url: String, method: String) {
Log.i(TAG, "callURL: url is " + url + "and method is " + method)
val urlRequest: UrlRequest? = builRequest(url, method)
urlRequest?.apply { urlRequest.start() }
}
/**
* Parse the domain name to obtain the host name.
*
* @param url Request URL.
* @return host Host name.
*/
private fun getHost(url: String): String? {
var host: String? = null
try {
val url1 = URL(url)
host = url1.host
} catch (e: MalformedURLException) {
Log.e(TAG, "getHost: ", e)
}
return host
}
fun setCallback(mCallback: UrlRequest.Callback?) {
callback = mCallback
}
}
Downloading the news
We will define a helper class to handle the request and parses the response into an ArrayList. The HQUIC kit will read certain number of bytes per time, for big responses the onReadCompleted method will be called more than once.
Code:
data class Article(val author:String,
val title:String,
val description:String,
val url:String,
val time:String)
class NewsClient(context: Context): UrlRequest.Callback() {
var hquicService: HQUICService? = null
val CAPACITY = 10240
val TAG="NewsDownloader"
var response:StringBuilder=java.lang.StringBuilder()
var listener:NewsClientListener?=null
init {
hquicService = HQUICService(context)
hquicService?.setCallback(this)
}
fun getNews(url: String, method:String){
hquicService?.sendRequest(url,method)
}
override fun onRedirectReceived(
request: UrlRequest,
info: UrlResponseInfo,
newLocationUrl: String
) {
request.followRedirect()
}
override fun onResponseStarted(request: UrlRequest, info: UrlResponseInfo) {
Log.i(TAG, "onResponseStarted: ")
val byteBuffer = ByteBuffer.allocateDirect(CAPACITY)
request.read(byteBuffer)
}
override fun onReadCompleted(
request: UrlRequest,
info: UrlResponseInfo,
byteBuffer: ByteBuffer
) {
Log.i(TAG, "onReadCompleted: method is called")
val readed=String(byteBuffer.array(), byteBuffer.arrayOffset(), byteBuffer.position())
response.append(readed)
request.read(ByteBuffer.allocateDirect(CAPACITY))
}
override fun onSucceeded(request: UrlRequest?, info: UrlResponseInfo?) {
//If everything is ok you can read the response body
val json=JSONObject(response.toString())
val array=json.getJSONArray("articles")
val list=ArrayList<Article>()
for (i in 0 until array.length()){
val article=array.getJSONObject(i)
val author=article.getString("author")
val title=article.getString("title")
val description=article.getString("description")
val time=article.getString("publishedAt")
val url=article.getString("url")
list.add(Article(author, title, description, url, time))
}
listener?.onSuccess(list)
}
override fun onFailed(request: UrlRequest, info: UrlResponseInfo, error: CronetException) {
//If someting fails you must report the error
listener?.onFailure(error.toString())
}
public interface NewsClientListener{
fun onSuccess(news:ArrayList<Article>)
fun onFailure(error: String)
}
}
Making the request
Define tue request properties
Code:
private val API_KEY="YOUR_API_KEY"
private val URL = "https://newsapi.org/v2/top-headlines?apiKey=$API_KEY"
private val METHOD = "GET"
Call the getNews function to start the request, if everything goes well, the list of news will be delivered on the onSuccess callback. If an error ocurs, the onFailure callback will be triggered.
Code:
private fun getNews() {
val country=Locale.getDefault().country
val url= "$URL&country=$country"
Log.e("URL",url)
val downloader=NewsClient(this)
downloader.apply {
[email protected]
getNews(url,METHOD)
}
}
override fun onSuccess(news: ArrayList<Article>) {
this.news.apply {
clear()
addAll(news)
}
runOnUiThread{
swipeRefreshLayout.isRefreshing=false
loadingDialog?.dismiss()
adapter?.notifyDataSetChanged()
}
}
override fun onFailure(error: String) {
val errorDialog=AlertDialog.Builder(this).apply {
setTitle(R.string.error_title)
val message="${getString(R.string.error_message)} \n $error"
setMessage(message)
setPositiveButton(R.string.ok){ dialog, _ ->
dialog.dismiss()
}
setCancelable(false)
create()
show()
}
}
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Conclusion
Is just a question of time for the QUIC protocol to become in the new standard of internet connections. For now you can get your apps ready to suppot it and provide the best user experience.
Test this demo: https://github.com/danms07/HQUICNews
Reference
Official Document
HQUIC sample code

Sending push notifications to specific users with Account and Push Kit [kotlin]

Sometimes you may need to show an alert to an specific user, for example, as a result of the interaction of another user (someone else commented your post), or to notify an event caused by your own business logic (Sign In detected in another device). In this article I'm going to show you how to bind a push token to a user id, so you can send personalized push notifications.
Previous requirements
A verified developer account
An app project with the HMS core SDK
Enabling the requred services
Go to your project in AppGallery Connect and make sure to enable Push Kit and Account Kit on the Manage APIs tab.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Now go to Push Kit on the left side panel to properly enabling the Push Service.
Integrting the SDKs
First, you must add the related dependencies for Account kit and Push kit. Add the next lines under dependencies of your app level build.gradle.
Code:
implementation 'com.huawei.hms:hwid:5.0.1.301'
implementation 'com.huawei.hms:push:5.0.1.300'
Note: please refer to the related document to obtain the most recent version of each SDK
Solution proposal
We want to bind a push token to the user's email (you can choose other user ID in your own implementation). We know we can get both in our app, but we don't know exaclty when. So, my suggestion is registering a BroadcastReceiver upon the app startup, which will wait for the token and the email. When the receiver has both, it will perform a POST operation to our server to save/update the binding. Once the operation is complete, the Receiver will perform a self unregister operation.
Code:
class MyBroadcastReceiver: BroadcastReceiver() {
companion object {
private val TAG="Receiver"
val PARAM="param"
val MAIL="mail"
val TOKEN="token"
val ACTION="ACTION_REGISTER_USER"
private val SERVER="https://a8a7ycwh8b.execute-api.us-east-2.amazonaws.com/Prod"
}
private var email:String?=null
private var token:String?=null
private var context:Context?=null
override fun onReceive(context: Context?, intent: Intent?) {
this.context=context
intent?.extras?.let {
val key=it.getString(PARAM)
val value=it.getString(key)
checkParamValues(key!!,value!!)
}
}
fun register(context:Context){
Log.d(TAG,"Registering Receiver")
context.registerReceiver(this,IntentFilter(ACTION))
}
private fun unregister(){
Log.d(TAG,"UnregisteringReceiver")
context?.unregisterReceiver(this)
}
private fun checkParamValues(key: String, value: String) {
Log.e(TAG,"Received $key")
when(key){
MAIL -> {
email=value
token?.let{registerInServer(value,it)}
}
TOKEN -> {
token=value
email?.let { registerInServer(it,value) }
}
}
}
private fun registerInServer(mail:String,token:String){
//perform registerOperation
CoroutineScope(Dispatchers.IO).launch {
val connection= URL(SERVER).openConnection() as HttpURLConnection
val outputStream=connection.apply{
requestMethod="POST"
doInput=true
doOutput=true
}.outputStream
val jsonObject=JSONObject().apply {
put(MAIL,mail)
put(TOKEN,token)
}
outputStream.write(jsonObject.toString().toByteArray())
Log.d("Response","${connection.responseCode} ${connection.responseMessage}")
//unregisterReceiver
unregister()
}
}
}
To ensure the receiver will be registered before we get the push token, we can define our own Application class and register the Receiver from the onCreate method. If we register a BroadcastReceiver by using the ApplicationContext, it will be alive as long as the app is running, that's very convenient for our purpose.
Code:
class MyApplication: Application() {
override fun onCreate() {
super.onCreate()
MyBroadcastReceiver().register(this)
}
}
Note: Don't forget to add your custom application class to your AndroidManifest.
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hms.demo.accountpush">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
If you already know how to implement Account kit and Push kit, maybe your problem is solved with this example. If not, please keep reading.
Integrating Push Kit
Create a class which inherits from HmsMessageService and override the methoods onNewToken and onMessageReceived.
Code:
class MyHmsMessageService: HmsMessageService() {
override fun onNewToken(token: String?) {
super.onNewToken(token)
token?.let {
Log.d("newToken",it)
publishToken(it)
}
}
private fun publishToken(token:String) {
val intent= Intent().apply {
action = MyBroadcastReceiver.ACTION
putExtra(MyBroadcastReceiver.PARAM,MyBroadcastReceiver.TOKEN)
putExtra(MyBroadcastReceiver.TOKEN,token)
}
sendBroadcast(intent)
}
override fun onMessageReceived(message: RemoteMessage?) {
message?.let {
Log.i("OnNewMessage",it.data)
val map=it.dataOfMap
for( key in map.keys){
Log.d("onNewMessage",map[key]!!)
}
}
}
}
Once the push token is delivered, we must report it to our BroadcastReceiver by using the publishToken funcion.
Add the next settings to your Android Manifest under <application>
Code:
<!--Enables the push automatic initialization-->
<meta-data
android:name="push_kit_auto_init_enabled"
android:value="true"/>
<!--Registers the custom HmsMessageService-->
<service
android:name=".MyHmsMessageService"
android:exported="false">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT"/>
</intent-filter>
</service>
This configuration will enable the automatic initialization, so the push token will be always delivered to the onNewToken method automatically.
Integrating Account Kit
First, we will ask if the app has been authorized previously. For this we can use the Silent Sign In API.
Code:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//We will try to use the silent sign in
val authParams = HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setScopeList(LoginActivity.SCOPES)
.createParams()
val service = HuaweiIdAuthManager.getService([email protected], authParams)
val task = service.silentSignIn()
task.addOnSuccessListener {//The sign in is successful, we can jump to the profile activity
//Apply for a token and register in the server side
val intent=Intent([email protected],ProfileActivity::class.java)
intent.putExtra(ProfileActivity.ACCOUNT,it)
startActivity(intent)
}
task.addOnFailureListener{//Redirect to the login activity
startActivity(Intent([email protected],LoginActivity::class.java))
finish()
}
}
}
If a user has authorized our app before, he will be logged in automatically. By other way he will be redirected to our login activity.
Create the layout of your login activity by using the Huawei Sign In button, provided on the Account kit SDK. This app will support Auth Code and ID Token.
Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity">
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android:id="@+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android:id="@+id/idtoken"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
app:hwid_color_policy="hwid_color_policy_blue"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:text="Authorization Code"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="Id Token"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/code" />
</androidx.constraintlayout.widget.ConstraintLayout>
Let's define the logic of the LoginActivity, as we want to get the user's email, we must apply for it by using the apropiated Scope. The user must approve the email permission manually at the authorization page, if not, the sign in response wont include it. In this case we are displayung a message to the user, asking for the email approval.
Code:
class LoginActivity : AppCompatActivity(), View.OnClickListener {
companion object {
private val AUTH_CODE = 100
private val AUTH_TOKEN = 200
private val TAG = "LoginActivity"
val SCOPES = listOf(Scope("email"))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
code.setOnClickListener(this)
idtoken.setOnClickListener(this)
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.code -> signInCode()
R.id.idtoken -> signInToken()
else -> {
}
}
}
private fun signInCode() {
val authParams = HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setAuthorizationCode()
.setScopeList(SCOPES)
.createParams()
val service = HuaweiIdAuthManager.getService(this, authParams)
startActivityForResult(service.getSignInIntent(), AUTH_CODE)
}
private fun signInToken() {
val authParams = HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setScopeList(SCOPES)
.createParams()
val service = HuaweiIdAuthManager.getService(this, authParams)
startActivityForResult(service.getSignInIntent(), AUTH_TOKEN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
AUTH_CODE -> handleAuthCodeResult(data)
AUTH_TOKEN -> handleAuthTokenResult(data)
}
}
private fun handleAuthTokenResult(data: Intent?) {
val authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data)
if (authHuaweiIdTask.isSuccessful) {
// The sign-in is successful, and the user's HUAWEI ID information and ID token are obtained.
val huaweiAccount = authHuaweiIdTask.result
checkAccount(huaweiAccount)
} else {
// The sign-in failed. No processing is required. Logs are recorded to facilitate fault locating.
Log.e(
TAG,
"sign in failed : " + (authHuaweiIdTask.exception as ApiException).message
)
}
}
private fun handleAuthCodeResult(data: Intent?) {
val authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data)
if (authHuaweiIdTask.isSuccessful) {
//The sign-in is successful, and the user's HUAWEI ID information and authorization code are obtained.
val huaweiAccount = authHuaweiIdTask.result
checkAccount(huaweiAccount)
} else {
// The sign-in failed.
Log.e(TAG, "sign in failed : " + (authHuaweiIdTask.exception as ApiException).message)
}
}
private fun jump(huaweiAccount: AuthHuaweiId) {
val intent = Intent(this, ProfileActivity::class.java)
intent.putExtra("account", huaweiAccount)
startActivity(intent)
finish()
}
private fun checkAccount(huaweiAccount: AuthHuaweiId) {
if (huaweiAccount.email.isNullOrEmpty()) {
Toast.makeText(
this, "Please allow email access in the authorization page", Toast.LENGTH_LONG
).show()
return
}
jump(huaweiAccount)
}
}
Now, from the profile activity (or the activity with the core functionality of your app) we must report the user's email to our Receiver.
Code:
companion object{
private val TAG="ProfileActivity"
val ACCOUNT="account"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
val huaweiId=intent.extras?.getParcelable<AuthHuaweiId>(ACCOUNT)
huaweiId?.apply {
name.text=displayName
mail.text=email
publishMail(email)
loadProfilePic(avatarUriString)
}
}
Bonus: Server side configuration
The BroadcastReceiver in this example is targeting a Lambda function on AWS, this is the code which makes the data insertion in a DynamoDB table.
Code:
'use strict'
const AWS = require('aws-sdk');
AWS.config.update({ region: "us-east-2" });
exports.handler = async (event) => {
// TODO implement
console.log(event);
const ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });
const documentClient = new AWS.DynamoDB.DocumentClient({ region: "us-east-2" });
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
const result=await writeDB(event,documentClient).catch(function(){
response.statusCode=400;
});
return response;
};
function writeDB(event, documentClient){
const entry = {
TableName: "PushBinding",
Item: {
mail: event.mail,
token: event.token
}
};
console.log(JSON.stringify(entry));
return documentClient.put(entry).promise();
}
Conclusion
Now you know how to associate a user id with a push token to send personalized push notifications. The Broadcast Receiver is used here to avoid stopping the app navigation by waiting for the push token or the user's email.
How many messages can the HUAWEI Push Kit server send at a time?

Upload Files to Huawei Drive with WorkManager

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
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)
Code:
// HMS Account Kit
implementation 'com.huawei.hms:hwid:5.1.0.301'
// HMS Drive Kit
implementation 'com.huawei.hms:drive:5.0.0.301'
// WorkManager
implementation "androidx.work:work-runtime-ktx:2.5.0"
// Kotlin Coroutines for asynchronously programming
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1'
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.
XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#D0D0D0"
tools:context=".MainActivity">
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView" />
<Button
android:id="@+id/btnCreateWork"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:backgroundTint="#1f70f2"
android:text="Create a Work"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnLogin" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:text="Upload File to Huawei Drive with WorkManager"
android:textAlignment="center"
android:textColor="#1f70f2"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:srcCompat="@drawable/ic_drive" />
</androidx.constraintlayout.widget.ConstraintLayout>
Permission for Storage
We need permission to access the phone’s storage. Let’s add the necessary permissions to our manifest.
Code:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
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.
Code:
class MainActivity : AppCompatActivity() {
private val TAG = "MainActivity"
private val REQUEST_SIGN_IN_CODE = 1001
private val REQUEST_STORAGE_PERMISSION_CODE = 1002
private lateinit var btnLogin: HuaweiIdAuthButton
private lateinit var btnCreateWork: Button
private var accessToken: String = ""
private var unionId: String = ""
private lateinit var driveCredential: DriveCredential
private val PERMISSIONS_STORAGE = arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnLogin = findViewById(R.id.btnLogin)
btnCreateWork = findViewById(R.id.btnCreateWork)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(PERMISSIONS_STORAGE, REQUEST_STORAGE_PERMISSION_CODE)
}
btnLogin.setOnClickListener {
signIn()
}
btnCreateWork.setOnClickListener {
if (accessToken.isEmpty() || unionId.isEmpty()) {
showToastMessage("AccessToken or UnionId is empty")
} else {
createWorkRequest(accessToken, unionId)
}
}
}
private fun signIn() {
val scopeList: MutableList<Scope> = ArrayList()
scopeList.apply {
add(Scope(DriveScopes.SCOPE_DRIVE))
add(Scope(DriveScopes.SCOPE_DRIVE_FILE))
add(Scope(DriveScopes.SCOPE_DRIVE_APPDATA))
add(HuaweiIdAuthAPIManager.HUAWEIID_BASE_SCOPE)
}
val authParams = HuaweiIdAuthParamsHelper(
HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM
)
.setAccessToken()
.setIdToken()
.setScopeList(scopeList)
.createParams()
val client = HuaweiIdAuthManager.getService(this, authParams)
startActivityForResult(client.signInIntent, REQUEST_SIGN_IN_CODE)
}
private val refreshAT = DriveCredential.AccessMethod {
/**
* Simplified code snippet for demonstration purposes. For the complete code snippet,
* please go to Client Development > Obtaining Authentication Information > Save authentication information
* in the HUAWEI Drive Kit Development Guide.
**/
[email protected] accessToken
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_SIGN_IN_CODE) {
val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful) {
val authAccount = authAccountTask.result
accessToken = authAccount.accessToken
unionId = authAccount.unionId
val driveCode = checkDriveCode(unionId, accessToken, refreshAT)
when (driveCode) {
DriveCode.SUCCESS -> {
showToastMessage("You are Signed In successfully")
}
DriveCode.SERVICE_URL_NOT_ENABLED -> {
showToastMessage("Drive is not Enabled")
}
else -> {
Log.d(TAG, "onActivityResult: Drive SignIn Failed")
}
}
} else {
Log.e(
TAG,
"Sign in Failed : " + (authAccountTask.exception as ApiException).statusCode
)
}
}
}
private fun checkDriveCode(
unionId: String?,
accessToken: String?,
refreshAccessToken: DriveCredential.AccessMethod?
): Int {
if (StringUtils.isNullOrEmpty(unionId) || StringUtils.isNullOrEmpty(accessToken)) {
return DriveCode.ERROR
}
val builder = DriveCredential.Builder(unionId, refreshAccessToken)
driveCredential = builder.build().setAccessToken(accessToken)
return DriveCode.SUCCESS
}
private fun createWorkRequest(accessToken: String, unionId: String) {
val uploadWorkRequest: WorkRequest = OneTimeWorkRequestBuilder<UploadWorker>()
.setInputData(
workDataOf(
"access_token" to accessToken,
"union_Id" to unionId
)
)
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
)
.setInitialDelay(1, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(applicationContext).enqueue(uploadWorkRequest)
showToastMessage("Work Request is created")
}
private fun showToastMessage(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
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.
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.
Code:
class UploadWorker(val appContext: Context, val params: WorkerParameters) :
CoroutineWorker(appContext, params) {
private val TAG = "UploadWorker"
private var accessToken: String = ""
private var unionId: String = ""
private lateinit var driveCredential: DriveCredential
companion object {
private val MIME_TYPE_MAP: MutableMap<String, String> = HashMap()
init {
MIME_TYPE_MAP.apply {
MIME_TYPE_MAP[".doc"] = "application/msword"
MIME_TYPE_MAP[".jpg"] = "image/jpeg"
MIME_TYPE_MAP[".mp3"] = "audio/x-mpeg"
MIME_TYPE_MAP[".mp4"] = "video/mp4"
MIME_TYPE_MAP[".pdf"] = "application/pdf"
MIME_TYPE_MAP[".png"] = "image/png"
MIME_TYPE_MAP[".txt"] = "text/plain"
}
}
}
override suspend fun doWork(): Result {
return withContext(Dispatchers.IO) {
try {
accessToken = inputData.getString("access_token") ?: ""
unionId = inputData.getString("union_Id") ?: ""
if (accessToken.isEmpty() || unionId.isEmpty()) {
Result.failure()
} else {
val driveCode = checkDriveCode(unionId, accessToken, refreshAT)
if (driveCode == DriveCode.SUCCESS) {
GlobalScope.launch { createAndUploadFile() }
} else {
Log.d(TAG, "onActivityResult: DriveSignIn Failed")
}
Result.success()
}
} catch (error: Throwable) {
Result.failure()
}
}
}
private fun checkDriveCode(
unionId: String?,
accessToken: String?,
refreshAccessToken: DriveCredential.AccessMethod?
): Int {
if (StringUtils.isNullOrEmpty(unionId) || StringUtils.isNullOrEmpty(accessToken)) {
return DriveCode.ERROR
}
val builder = DriveCredential.Builder(unionId, refreshAccessToken)
driveCredential = builder.build().setAccessToken(accessToken)
return DriveCode.SUCCESS
}
private val refreshAT = DriveCredential.AccessMethod {
/**
* Simplified code snippet for demonstration purposes. For the complete code snippet,
* please go to Client Development > Obtaining Authentication Information > Save authentication information
* in the HUAWEI Drive Kit Development Guide.
**/
[email protected] accessToken
}
private fun buildDrive(): Drive? {
return Drive.Builder(driveCredential, appContext).build()
}
private fun createAndUploadFile() {
try {
val appProperties: MutableMap<String, String> =
HashMap()
appProperties["appProperties"] = "property"
val file = com.huawei.cloud.services.drive.model.File()
.setFileName("DriveWithWorkManager")
.setMimeType("application/vnd.huawei-apps.folder")
.setAppSettings(appProperties)
val directoryCreated = buildDrive()?.files()?.create(file)?.execute()
val path = appContext.getExternalFilesDir(null)
val fileObject = java.io.File(path.toString() + "/NatureAndMan.jpg")
appContext.getExternalFilesDir(null)?.absolutePath
val mimeType = mimeType(fileObject)
val content = com.huawei.cloud.services.drive.model.File()
.setFileName(fileObject.name)
.setMimeType(mimeType)
.setParentFolder(listOf(directoryCreated?.id))
buildDrive()?.files()
?.create(content, FileContent(mimeType, fileObject))
?.setFields("*")
?.execute()
// Resumable upload for files larger than 5 MB.
/*
val fileInputStream = FileInputStream(fileObject)
val inputStreamLength = fileInputStream.available()
val streamContent = InputStreamContent(mimeType, fileInputStream)
streamContent.length = inputStreamLength.toLong()
val content = com.huawei.cloud.services.drive.model.File()
.setFileName(fileObject.name)
.setParentFolder(listOf(directoryCreated?.id))
val drive = buildDrive()
drive!!.files().create(content, streamContent).execute()
*/
} catch (exception: Exception) {
Log.d(TAG, "Error when creating file : $exception")
}
}
private fun mimeType(file: File?): String? {
if (file != null && file.exists() && file.name.contains(".")) {
val fileName = file.name
val suffix = fileName.substring(fileName.lastIndexOf("."))
if (MIME_TYPE_MAP.keys.contains(suffix)) {
return MIME_TYPE_MAP[suffix]
}
}
return "*/*"
}
}
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.
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.
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
Interesting.

Building a News Client with Network Kit and MVVM

Most android applications download it's content from the cloud (commonly a REST API) getting ready to parse and display that information with lists and menus in order to display dynamic content or provide a personalized experience. There are some third party libraries designed to consume a REST API (like Retrofit) or to download media content (like Glide and Picasso). This time, let me introduce you the new Huawei Network Kit.
What is nework kit?
Network kit is the new Huawei's System SDK designed to simplify the communications with web services by providing 2 main connection modes:
Rest Client
HTTP Client
Network kit supports QUIC connections automatically, that means if the Web service supports QUIC or migrates to QUIC, your app will keep working without require any change. In addition, this kit is pretty similar to the well known Retrofit, so, if you have previous experience with Retrofit, you will be able to integrate Network Kit withount complications.
Previously, we made a News client by using the HQUIC kit. In this article we are going to develop a news client application by using the new Huawei Network Kit.
Previous requirements
A developer account in newsapi.org
Android Studio 4.0 or later and the kotlin plugin
Setting up the project
Network kit doesn't require to setup a project in AGC, but you still need to add the Huawei Maven repositories to your project-level build.gradle:
Java:
buildscript {
ext.kotlin_version = "1.4.31"
repositories {
...
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.2"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
...
maven {url 'https://developer.huawei.com/repo/'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Go to the official documents and look for the Network kit latest version under version change history. Once you have found the latest version available, add it to yout app-level build.gradle as follows
Java:
implementation 'com.huawei.hms:network-embedded:5.0.1.301'
We will use Moshi to parse the response from the web service, let's add the related dependencies and the kapt plugin to proccess the annotations.
Java:
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
android{
...
}
dependencies {
...
implementation 'com.huawei.hms:network-embedded:5.0.1.301'
implementation 'com.squareup.moshi:moshi:1.11.0'
implementation "com.squareup.moshi:moshi-kotlin:1.11.0"
kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.11.0'
...
}
To display the news in a list, we must add RecyclerView and CardView to our project and must enable the DataBinding library to make our job easier.
Java:
android {
...
//Enabling DataBinding and ViewBinding
buildFeatures{
viewBinding true
dataBinding true
}
...
}
dependencies {
...
//MVVM dependencies
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0"
//DataBinding dependency
kapt "com.android.databinding:compiler:3.1.4"
//Layout dependencies
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation "androidx.cardview:cardview:1.0.0"
...
}
We are ready to start the project.
Building the request
First of all, Network kit must be initialized, let's create an Application class to do this job
NetworkApplication.kt
Java:
class NetworkApplication: Application() {
companion object {
const val TAG="Network Application"
}
override fun onCreate() {
super.onCreate()
initNetworkKit()
}
private fun initNetworkKit() {
// Initialize the object only once, upon the first call.
NetworkKit.init(this ,object : NetworkKit.Callback() {
override fun onResult(result: Boolean) {
if (result) {
Log.i(TAG, "Networkkit init success")
} else {
Log.i(TAG, "Networkkit init failed")
}
}
})
}
}
To make sure this code will be excecuted upon each startup, we must specify this class inside the application element in our AndroidManifest.xml. Let's add the required permissions too.
XML:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name=".NetworkApplication"
android:requestLegacyExternalStorage="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.NetworkKitDemo"
android:usesCleartextTraffic="true">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Now, we must create the data models wich Moshi will use to parse the response
NewsResponse.kt
Java:
@JsonClass(generateAdapter = true)
data class NewsResponse(
@Json(name = "status") val status: String?,
@Json(name = "totalResults") val totalResults: Int?,
@Json(name = "articles") val articles: List<Article>
)
@JsonClass(generateAdapter = true)
data class Article(
@Json(name = "source") val source: Source?,
@Json(name = "author") val author: String?,
@Json(name = "title") val title: String?,
@Json(name = "description") val description: String?,
@Json(name = "url") val url: String?,
@Json(name = "urlToImage") val urlToImage: String?,
@Json(name = "publishedAt") val publishedAt: String?,
@Json(name = "content") val content: String?
)
@JsonClass(generateAdapter = true)
data class Source(
@Json(name = "id") val id: String?,
@Json(name = "name") val name: String?
)
Network kit porvides 2 operation modes, we will use the REST Client to get the Top headlines in the user's country and the HTTP Client mode to download the picture of each Article. We will create a singleton class called NetworkKitHelper.
Let's take a look to the REST Client mode:
NetworkKitHelper.kt
Java:
object NetworkKitHelper {
const val TAG: String = "HTTPClient"
//Your API key from newsapi.org
val apiKey = Keys.readApiKey()
fun createNewsClient(): NewsService {
val restClient = RestClient.Builder()
.httpClient(HttpClient.Builder().build())
.baseUrl("https://newsapi.org/v2/")//Specify the API base URL, this is useful if you will consume multiple paths of the same API
.build()
return restClient.create(NewsService::class.java)
}
//Declare a Request API
interface NewsService {
//Use the GET annotation to specify the path
@GET("top-headlines/")
fun getTopHeadlines(/* use the Query annotation to specify a query parameter in the request*/
@Query("apiKey") apiKey: String? = "",
@Query("country") country: String
): Submit<String?>?
}
fun loadTopHeadlines(sampleService: NewsService, listener: NewsClientListener?,country:String=Locale.getDefault().country) {
sampleService.getTopHeadlines(apiKey,country)?.enqueue(object : Callback<String?>() {
@Throws(IOException::class)
override fun onResponse(submit: Submit<String?>?, response: Response<String?>) {
// Obtain the response. This method will be called if the request is successful.
val body = response.body
body?.let {
try {
val moshi = Moshi.Builder().build()
val adapter = moshi.adapter(NewsResponse::class.java)
val news = adapter.fromJson(it)
news?.let { myNews ->
listener?.onNewsDownloaded(myNews.articles)
}
} catch (e: JSONException) {
Log.e("excepion", e.toString())
}
}
}
override fun onFailure(submit: Submit<String?>?, exception: Throwable?) {
// Obtain the response. This method will be called if the request fails.
Log.e("LoadTopHeadlines", "response onFailure = " + exception?.message)
}
})
}
interface NewsClientListener {
fun onNewsDownloaded(news: List<Article>)
}
}
Put special attention to the loadTopHeadlines function. As you can see, there aren't coroutines or threads defined, we are using the enqueue API instead. By this way Network Kit will handle the request in asynchronous mode for us.
If the API call is successfull, we will use Moshi to parse the response into data objects. By other way, we will be notified about the error in the onFailure callback. Once the response has been parsed, NetworkKitHelper will repor the news to the specified NewsClientListener.
Let's add the code to download the preview pics:
NetworkKitHelper.kt (Adding)
Java:
object NetworkKitHelper {
private val httpClient: HttpClient = createClient()
private fun createClient(): HttpClient {
return HttpClient.Builder()
.callTimeout(1000)
.connectTimeout(10000)
.build()
}
fun createRequest(url: String): Request {
return httpClient.newRequest()
.url(url)
.method("GET")
.build()
}
fun httpClientEnqueue(request: Request, listener: HttpClientListener? = null) {
httpClient.newSubmit(request).enqueue(object : Callback<ResponseBody?>() {
@Throws(IOException::class)
override fun onResponse(
submit: Submit<ResponseBody?>?,
response: Response<ResponseBody?>
) {
// Process the response if the request is successful.
Log.i(TAG, "response code:" + response.code)
response.body?.let {
listener?.onSuccess(it.bytes())
}
}
override fun onFailure(submit: Submit<ResponseBody?>?, throwable: Throwable?) {
// Process the exception if the request fails.
Log.w(TAG, "response onFailure = ${throwable?.message}")
}
})
}
interface HttpClientListener {
fun onSuccess(body: ByteArray)
}
}
As well as with the REST Client mode, we are able to enqueue HTTP Requests and define a callback for each one. In this case, we are receiving a byte array which will be used to create and display a bitmap.
Here we will face a complication. If we try to store the bitmap in the same data class as the Article, Moshi will cause a reflection error at compilation time. To solve this, we will define a new class to store the article and be responsible to load the bitmap, by doing so, we will be able to load the news as soon as we get them and then using the observer pattern, the bitmap will be added to the view as soon as it's ready.
ArticleModel.kt
Java:
class ArticleModel(val article: Article) : NetworkKitHelper.HttpClientListener {
private val _bitmap= MutableLiveData<Bitmap?>().apply{postValue(null)}
val bitmap: LiveData<Bitmap?> =_bitmap
init {
loadBitmap()
}
fun loadBitmap() {
article.urlToImage?.let{
val request=NetworkKitHelper.createRequest(it)
NetworkKitHelper.httpClientEnqueue(request, this)
}
}
override fun onSuccess(body: ByteArray) {
val bitmap= BitmapFactory.decodeByteArray(body, 0, body.size)
val resizedBitmap = Bitmap.createScaledBitmap(bitmap, 1000, 600, true)
_bitmap.postValue(resizedBitmap)
}
}
As soon as any instance of ArticleModel is created, it will enqueue an HTTP request async for the preview pic. If the call is successfull, we will receive a ByteArray in the onSuccess callback to create our bitmap from it and let the observer know the bitmap is ready to be displayed.
Sending the request
Let's create a ViewModel which will be responsible to invoke the API and store the data. Here we will use the observer pattern to let the observer know the Articles are ready to be displayed.
MainViewModel.kt
Java:
class MainViewModel : ViewModel(), NetworkKitHelper.NewsClientListener {
private val _articles = MutableLiveData<ArrayList<ArticleModel>>().apply { value = ArrayList() }
val articles: LiveData<ArrayList<ArticleModel>> = _articles
fun loadTopHeadlines(){
articles.value?.let{
if(it.isEmpty()) getTopHeadlines()
else return
}
}
private fun getTopHeadlines() {
NetworkKitHelper.loadTopHeadlines(NetworkKitHelper.createNewsClient(),this)
}
override fun onNewsDownloaded(news: List<Article>) {
val list=ArrayList<ArticleModel>()
for (article: Article in news) {
list.add(ArticleModel(article))
}
_articles.postValue(list)
}
}
To avoid downloading the news again when the user rotates the screen, we are defining the loadTopHeadlines function. It will only make the request if the list of articles is empty.
Displaying the Articles
We will use DataBinding to quicly display our news in a RecyclerView on the MainActivity, let's take a look to the main layout
activity_main.xml
XML:
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<data class="MainBinding"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler"
android:layout_height="match_parent"
android:layout_width="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Now we must define the card wich will be rendered for each article
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
article_card.xml
XML:
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data class="ArticleBinding">
<variable
name="item"
type="com.hms.demo.networkkitdemo.ArticleModel" />
</data>
<androidx.cardview.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginHorizontal="5dp"
android:layout_marginVertical="5dp"
card_view:cardCornerRadius="15dp"
card_view:cardElevation="20dp"
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/pic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:contentDescription="@string/desc"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="1.0"
card_view:layout_constraintStart_toStartOf="parent"
card_view:layout_constraintTop_toBottomOf="@+id/articleTitle"
card_view:shapeAppearanceOverlay="@style/roundedImageView"
tools:srcCompat="@tools:sample/avatars" />
<TextView
android:id="@+id/articleTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@{item.article.title}"
android:textAlignment="viewStart"
android:textSize="24sp"
android:textStyle="bold"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="0.498"
card_view:layout_constraintStart_toStartOf="parent"
card_view:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/desc"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="@{item.article.description}"
android:textSize="20sp"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintStart_toStartOf="parent"
card_view:layout_constraintTop_toBottomOf="@+id/pic" />
<TextView
android:id="@+id/source"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="@{item.article.source.name}"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintStart_toStartOf="parent"
card_view:layout_constraintTop_toBottomOf="@+id/desc"
card_view:layout_constraintVertical_bias="0.09" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</layout>
The ArticleBinding class will be responsible to fill the view with the values in it's ArticleModel instance for us. That's the magic of DataBinding.
As you may know, to display elements in a RecyclerView we need an Adapter, so let's define it
NewsAdapter.kt
Java:
class NewsAdapter: RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() {
var articles:List<ArticleModel> =ArrayList()
class NewsViewHolder(private val binding:ArticleBinding): RecyclerView.ViewHolder(binding.root) {
fun bind(item:ArticleModel){
binding.item=item
item.bitmap.observe(binding.root.context as LifecycleOwner){
it?.let{
binding.pic.setImageBitmap(it)
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val inflater=LayoutInflater.from(parent.context)
val binding=ArticleBinding.inflate(inflater,parent,false)
return NewsViewHolder(binding)
}
override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
holder.bind(articles[position])
}
override fun getItemCount(): Int {
return articles.size
}
}
Put special attention to the bind function of the NewsViewHolder class, from here we are telling to the ArticleBinding instance what is the information we want to display in the view. Also, we are using the observer pattern to update the ImageView once the article's preview pic has been downloaded.
Finally, is time to join everything through the MainActivity
MainActivity.kt
Java:
class MainActivity : AppCompatActivity() {
companion object {
const val TAG="Main"
}
private lateinit var binding:MainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= MainBinding.inflate(layoutInflater)
binding.lifecycleOwner = this
setContentView(binding.root)
val viewModel:MainViewModel=ViewModelProvider(this).get(MainViewModel::class.java)
val adapter=NewsAdapter()
viewModel.articles.observe(this){
adapter.articles=it
adapter.notifyDataSetChanged()
}
binding.recycler.adapter=adapter
viewModel.loadTopHeadlines()
}
}
Final result
Tips & Tricks
If your app will consume a REST API with Kotlin, is better to use Moshi instead of gson because Moshi can understand the kotlin's not-nullable types.
If you will use API keys to authenticate your client with the server, is better to use the NDK to hide your KEY and prevent it from being obtained by using reverse engineering. Let's use the Rahul Sharma's hidding method. (Make sure to download the Android NDK from the SDK Manager)
1. Swithch to the Project view and create a jni directory under the main directory.
2. Under the jni directory add the next 3 files:
Android.mk
Code:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := keys
LOCAL_SRC_FILES := keys.c
include $(BUILD_SHARED_LIBRARY)
Application.mk
Code:
APP_ABI := all
Keys.c (Put here your API key)
Code:
#include <jni.h>
JNIEXPORT jstring JNICALL
Java_com_hms_demo_networkkitdemo_Keys_getApiKey(JNIEnv *env, jclass instance) {
return (*env)->NewStringUTF(env, "PUT_HERE_YOUR_API_KEY");
}
3. Switch back to the Android View and create a Keys kotlin object
Keys.kt
Java:
object Keys {
init {
System.loadLibrary("keys")
}
private external fun getApiKey(): String?
public fun readApiKey(): String? { //use this method for String
return getApiKey()
}
}
4. Tell gradle you will use NDK by adding the next code inside android
build.gradle (app-level)
Java:
plugins {
...
}
android {
...
externalNativeBuild {
ndkBuild {
path 'src/main/jni/Android.mk'
}
}
}
dependencies {
...
}
Finally, modify the NetworkKitHelper object to read the API key from the native library.
NetworkKitHelper.kt (Modifying)
Code:
object NetworkKitHelper {
val apiKey = Keys.readApiKey()
}
Conclusion
By using Network kit your app will be ready to perform requests over QUIC or HTTP/2 without writting extra code. The REST Client mode and it's annotations are helpful to to quickly consume a REST API without taking care about Threads or Coroutines. And finally, the HTTP Client mode is useful to download preview images or any other stuff which is not a JSON.
References
Read In Forum
Network Kit official Docs
Hiding Secret/Api key from reverse engineering in Android using NDK
Moshi
Hi, i have one question if we use network kit then we no need to use any third-party like volley, Retrofit?
Is it faster and easy to use than Retrofit library?

Categories

Resources