Tag

androidwave

Browsing

In this blog, We’ll learn coroutines background processing by creating a small project, that simply displays an image to the UI.

Objective

  • Get Image from URL – So first we’re going to get an image from URL and obviously we can not do that on the main thread. So we need a background thread to do that. And we’re going to this with Coroutines.
  • Apply Processing – Next stuff is after downloading the image. We’re going to use another dispatcher to process that image. So here we’re going to apply a filter to that image. So that we transform it in a certain way. We’re going to convert it to black and white. We will do that in a separate coroutine for background processing.
  • Show it on ImageView – Finally, we’re going to show it on ImageView.

So it quite a simple idea, But the way we do it nicely. Because we are going to use coroutine for background processing. So while we are working live project we can understand how we can perform background processing with the bits of help of Coroutines.

Requirements

Importantly I want to mention here that there are some requirements for this example.

  • Android Studio – First of all you have to AndroidStudio installed in your machine.
  • Android Knowledge – You would have some Android development knowledge.

All right just go ahead and jump into the Android Studio.

Let’s create a new project with basic template. So first of all, I’m going to create a basic interface and you not have to worry about it, you can download the source code from bottom of this blog.

Add permission

Obviously, first thing we are going to download an image from server so we have to require Internet permission. So let open the android manifest add it.

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

I’m going to use this URL here, So this is what we will downloading and this is what we will processing.

<?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=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="500dp"
        android:layout_height="500dp"
        android:scaleType="fitCenter"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"
        app:srcCompat="@mipmap/ic_launcher" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Alright moving on we have a layout that has basically two elements. It has ProgressBar that will just show that something is going on in IO dispatcher. and it has an ImageView that is currently hidden. So this will become visible when we actually have something to display. and then we’ll hide the progressbar.

MainActivity

Create Filter

package com.backgroundprocessingexample

import android.graphics.Bitmap
import android.graphics.Color

object Filter {

    fun apply(source: Bitmap): Bitmap {
        val width = source.width
        val height = source.height
        val pixels = IntArray(width * height)
        // get pixel array from source
        source.getPixels(pixels, 0, width, 0, 0, width, height)

        var R: Int
        var G: Int
        var B: Int
        var index: Int
        var threshHold: Int

        for (y in 0 until height) {
            for (x in 0 until width) {
                // get current index in 2D-matrix
                index = y * width + x
                // get color
                R = Color.red(pixels[index])
                G = Color.green(pixels[index])
                B = Color.blue(pixels[index])
                val grey = (R + G + B) / 3
                pixels[index] = Color.rgb(grey, grey, grey)
            }
        }

        // output bitmap
        val bitmapOut = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
        bitmapOut.setPixels(pixels, 0, width, 0, 0, width, height)
        return bitmapOut
    }
}

one things that I added here it is the Filter. Now this filter has a function fun apply(source: Bitmap) on a bitmap and it’s simply converted to a bitmap and It’s simply converted to a bitmap out to a another image.

What this filter does, It converts images to black & white. It does handle some processing because it goes pixel by pixel to convert it into black & white. That will take some processing power. So that a background job, So we can apply our coroutines to it. We can’t do it on the main thread or It should not do this in main thread.

    // Add Coroutines Dependency
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1'

So here in the dependency first of all go ahead and copy the above dependencies. After adding these dependencies let go ahead and sync the project.

Now let’s open the MainActivity, So first i want to load image here from URL to local bitmap. then we want to put that bitmap in our ImageView. So I’m creating a kotlin function.

    private fun getImageFromUrl(): Bitmap =
            URL(IMAGE_URL).openStream().use {
                BitmapFactory.decodeStream(it)
            }

    private fun loadImage(bmp: Bitmap) {
        progressBar.visibility = View.GONE
        imageView.setImageBitmap(bmp)
        imageView.visibility = View.VISIBLE
    }

So this function simply returns a bitmap of whatever is returned from decode stream. Now Important thing is this is a network call. So we can not do that in main thread. So what we’ll like to do is we would like to open up a coroutines scope and do that call inside the scope on the IO dispatcher.

 coroutineScope.launch {
            val remoteImageDeferred = coroutineScope.async(Dispatchers.IO) {
                getImageFromUrl()
            }
            val imageBitmap = remoteImageDeferred.await()
            //loadImage(imageBitmap)
            launch(Dispatchers.Default) {
             val filterBitmap =   Filter.apply(imageBitmap)
                withContext(Dispatchers.Main) {
                    loadImage(filterBitmap)
                }

               // Log.i(MainActivity.TAG, "Default. Thread: ${Thread.currentThread().name}")
            }
        }

So let create a coroutines scope, here I’m going to open the main scope. Because we have to update UI from IO. Otherwise, we can’t update UI from another thread, It has to from main thread.

So the final output is

package com.backgroundprocessingexample

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.net.URL

class MainActivity : AppCompatActivity() {

    private val IMAGE_URL = "http://androidwave.com/wp-content/uploads/2018/12/useful-tools-for-logging-debugging-in-android.png.webp"
    private val coroutineScope = CoroutineScope(Dispatchers.Main)


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        coroutineScope.launch {
            val remoteImageDeferred = coroutineScope.async(Dispatchers.IO) {
                getImageFromUrl()
            }
            val imageBitmap = remoteImageDeferred.await()
            //loadImage(imageBitmap)
            launch(Dispatchers.Default) {
             val filterBitmap =   Filter.apply(imageBitmap)
                withContext(Dispatchers.Main) {
                    loadImage(filterBitmap)
                }

               // Log.i(MainActivity.TAG, "Default. Thread: ${Thread.currentThread().name}")
            }
        }

    }

    private fun getImageFromUrl(): Bitmap =
            URL(IMAGE_URL).openStream().use {
                BitmapFactory.decodeStream(it)
            }

    private fun loadImage(bmp: Bitmap) {
        progressBar.visibility = View.GONE
        imageView.setImageBitmap(bmp)
        imageView.visibility = View.VISIBLE
    }
}

Conclusion

That all, this way you can perform background jobs using coroutines in Kotlin. Keep in touch for more coroutines tutorials

In this post, we gonna talk about firebase in-app messaging in android.

Overview

Firebase In-App Messaging helps you engage your app’s active users by sending them targeted, contextual message. Encourage them to use key app features. For example, you can send an in-pp message to get users to subscribe, watch a video, complete a level, or buy an items. I’m sure you guys familiar. If you had android app you often get in-app message.

You can customized message as card, banners, models, or images. You can also set up a trigger so that they appear exactly when they’d benefit. It is very similar to cloud messaging, except for messages sent to the app, not a device. So if you talk about cloud messaging.

Uses of In-App Messaging

You should use Firebase In-App Messaging to encourage exploration and discovery. Highlight a sale or coupon in your eCommerce app. Give clues or tips in your game. Prompt a like or share in your social media app. These types of things, So kind of different use case or messaging.

Key Capabilities of In App Messaging

  • Send relevant, engaging messages
  • Sends messages when they are most needed, while users are actually in your app.
  • Promote a big sale when users visit your In-app store. etc.
  • Target messages by audience or behavior.
    • Work with Analytics and Predictions to give you tools to deliver the message to the user you would most like to reach
    • Send messages based on user’s demographics, past behaviors, or even predictions of their future behaviors.
  • Create flexible, custom alerts –
    • You can create a flexible, custom alert and have the ability to customize your style appearance display triggers and content.
    • These will help you do everything from sending promotional offers to getting users to update a new version of the app.

Implementations Step

Now I want to show you, how you can setup and configure to use In App Messaging for Firebase.

  • Connect your app – Start by adding Firebase to your app in the firebase console
  • Integrates the SDK – Add the firebase In-App Messaging SDK to your app via Gradle.
  • Create your first message – Visit the Firebase console to write, customize, and target your first message.

Connect your app

Let’s open android studio, and create a simple project. For now It doesn’t have anything extra on it. It just MainActivity that’s empty.

The first thing we’re gonna to do we’re going to add this project to Firebase. Fo doing that we need to know is the package name, In this example, I’m using com.firebaseinappmessaging .

Now let’s go to the firebase console and go to the project. Then just add the app and go through the steps the adding an app by entering package name. Still, you are facing any issue, follow this article.

Now you have to download json file, So go to settings and download on google-service.json file in app folder.

Integrates the SDK

Now back to the Android Studio, Now we have to update Gradle file. So go to the project build.gradle file and add these dependencies. Something like below

    // Import the Firebase BoM
    implementation 'com.google.firebase:firebase-inappmessaging-display-ktx:19.1.5'
    implementation 'com.google.firebase:firebase-analytics-ktx:18.0.2'

Let’s sync the project, That all about configuration. For sending a test message you have to need AppInstaceId, Basically firebase console allow us send messaging to specific device.

<?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=".MainActivity">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="16dp"
        android:text="@string/warning_fresh_install"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/instanceIdText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/instanceIdText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="@string/warning_fresh_install"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        tools:text="Device Instance ID: 1234" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/eventTriggerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:background="@color/purple_200"
        android:text="@string/button_text"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.firebaseinappmessaging

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.inappmessaging.FirebaseInAppMessaging
import com.google.firebase.inappmessaging.display.ktx.FirebaseInAppMessagingDisplayKtxRegistrar
import com.google.firebase.installations.FirebaseInstallations
import com.google.firebase.ktx.Firebase
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private lateinit var firebaseIam: FirebaseInAppMessaging
    //private lateinit var firebaseAnalytics: FirebaseAnalytics
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // firebaseAnalytics = FirebaseAnalytics.getInstance(this)
        firebaseIam = FirebaseInAppMessaging.getInstance()

        firebaseIam.isAutomaticDataCollectionEnabled = true
        firebaseIam.setMessagesSuppressed(false)

        eventTriggerButton.setOnClickListener { view ->
            //firebaseAnalytics.logEvent("engagement_party", Bundle())
            firebaseIam.triggerEvent("engagement_party")
        }

        // Get and display/log the Instance ID
        FirebaseInstallations.getInstance().id.addOnSuccessListener {
            instanceIdText.text = getString(R.string.instance_id_fmt, it)
            Log.d(TAG, "InstanceId: $it")
        }
//            .addOnSuccessListener(object : OnSuccessListener<InstanceIdResult> {
//                override fun onSuccess(instanceIdResult: InstanceIdResult) {
//                    val instanceId = instanceIdResult.id
//                    instanceIdText.text = getString(R.string.instance_id_fmt, instanceId)
//                    Log.d(TAG, "InstanceId: $instanceId")
//                }
//            })

        addClickListener()
    }
    private fun addClickListener() {
        val listener = InAppMessageClickListener()
        firebaseIam.addClickListener(listener)
    }

    private fun suppressMessages() {
        firebaseIam.setMessagesSuppressed(true)
    }

    private fun enableDataCollection() {
        // Only needed if firebase_inapp_messaging_auto_data_collection_enabled is set to
        // false in AndroidManifest.xml
        firebaseIam.isAutomaticDataCollectionEnabled = true
    }

    companion object {

        private const val TAG = "FirebaseInAppMessaging"
    }
}
package com.example.firebaseinappmessaging

import android.util.Log
import com.google.firebase.inappmessaging.FirebaseInAppMessagingClickListener
import com.google.firebase.inappmessaging.model.Action
import com.google.firebase.inappmessaging.model.InAppMessage


class InAppMessageClickListener : FirebaseInAppMessagingClickListener {

    override fun messageClicked(inAppMessage: InAppMessage, action: Action) {
        // Determine which URL the user clicked
        val url = action.actionUrl

        // Get general information about the campaign
        val metadata = inAppMessage.campaignMetadata

        Log.d("AppTest", "URL is: " + url)
        Log.d("AppTest", "Meta Data: " + metadata)
    }
}

In this article, I will show, how to create a CardView in React Native, Which will work perfectly in android and iOS both. So let’s started.

Objectives

Basically, the purpose of the example is to design and CardView component in React Native and use it whenever we need it. Why it should component? The reason is we can use this CardView in other parts of the application. We might have a different item that we want to present in CardView.

Let suppose you’re building an app, how have to show products inside the card on the main screen. Now avoid repeating cardview style definition agin and again. We can create a separate component. Let create a new react native project.

Create a react native application

let move to IDE, create a new react native project and create separate package named is components. Here I’m creating a new file here name it Card.js. The name is up to you

import React from 'react';
import { View, StyleSheet } from 'react-native';

const Card = props => {};

export default Card;
 

So here I simply created a function component named is Card.js and export as default. Now it’s all about presentation here, So let style this card view

import React from 'react';
import { View, StyleSheet } from 'react-native';

const Card = props => {
  return (
    <View style={{ ...styles.card, ...props.style }}>{props.children}</View>
  );
};

const styles = StyleSheet.create({
  card: {
    shadowColor: 'black',
    shadowOffset: { width: 0, height: 2 },
    shadowRadius: 6,
    shadowOpacity: 0.26,
    elevation: 8,
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 10
  }
});

export default Card;
  

That all, our components is ready for use. Let import this component in main app

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';

import {Colors} from 'react-native/Libraries/NewAppScreen';
import Card from './src/components/Card';

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView style={styles.container}>
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Basic CardView Example</Text>
        </Card>
      </SafeAreaView>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    margin: 16,
    alignItems: 'center', // Centered horizontally
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.white,
  },
  card: {
    height: 200,
    width: '100%',
    backgroundColor: '#f18484',
    justifyContent: 'center', //Centered vertically
    alignItems: 'center', // Centered horizontally
  },
});

export default App;

In this blog, we will learn how to use retrofit with coroutines Kotlin in android application, with the help of an example. So we are actually building an application in android using Coroutines, Retrofit and MVVM, and so on. So lets started.

Objectives

Basically, the purpose of the project is to get the list of users information from the endpoints and display it to users in RecyclerView. I’m listing them below of these are objectives of this Retrofit coroutines example blog.

  • Get a list of user’s info from an endpoint using REST API. Basically
  • Use coroutines with Retrofit and MVVM
  • Display the user’s info in a RecyclerView

So the main idea is to show you, how you can build a professional application using a proper architecture with Retrofit and using coroutines to get some information from a webserver. so that is what we are building.

Requirements

Now, there are some requirements for this retrofit coroutines example app. These are listed below

  • Android knowledge
  • Retrofit
  • MVVM

So idea is, I’m not going to details of these, you have to basic idea of these items. You should know how retrofit works with MVVM. I’m going to focus, this example on coroutines that work with Retrofit and MVVM.

All right guys, so lets started quickly with this example app. Open AndroidStudio and create a new android project with some template.

Setting up the project

Let wait for sync of project, that recently you created. And first of all let’s add internet permission in AndroidManifest that is obvious, Because we are communicating with backend APIs. So we do need that

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

All right then next step is we have to add below dependency in app build.gradle.

  • RecyclerView
  • Glide
  • Retrofit
  • Lifecycle extensions
  • Coroutines
    // RecyclerView dependency
    implementation "androidx.recyclerview:recyclerview:1.1.0"
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
    // Glide dependency
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    // Retrofit dependency
    implementation 'com.squareup.retrofit2:retrofit:2.7.1'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
    // Lifecycle dependency
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    // Coroutines dependency
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'

Backend API Endpoint and JSON

So first of all, we require a REST API, that we have to consume in this project. You can use whatever you required. For now, I’m consuming this URL and json response is

{
  "page": 1,
  "per_page": 6,
  "total": 12,
  "total_pages": 2,
  "data": [
    {
      "id": 1,
      "email": "george.bluth@reqres.in",
      "first_name": "George",
      "last_name": "Bluth",
      "avatar": "https://reqres.in/img/faces/1-image.jpg"
    },
    {
      "id": 2,
      "email": "janet.weaver@reqres.in",
      "first_name": "Janet",
      "last_name": "Weaver",
      "avatar": "https://reqres.in/img/faces/2-image.jpg"
    },
    {
      "id": 3,
      "email": "emma.wong@reqres.in",
      "first_name": "Emma",
      "last_name": "Wong",
      "avatar": "https://reqres.in/img/faces/3-image.jpg"
    }
    .
    .
    .
  ]
}

Create user Model

Now, we are following the MVVM design pattern in this coroutines example. So I’m creating a data class for parsing above JSON resonse. Let create a data class named is UserList.kt

package com.retrofitcoroutines.example.model

import com.google.gson.annotations.SerializedName

data class UserList(
    @SerializedName("page") val page: Int,
    @SerializedName("per_page") val per_page: Int,
    @SerializedName("total") val total: Int,
    @SerializedName("total_pages") val total_pages: Int,
    @SerializedName("data") val data: List<User>
)
 

Let’s create another data class named User.kt

package com.retrofitcoroutines.example.model

import com.google.gson.annotations.SerializedName

data class User(
    @SerializedName("id") val id : Int,
    @SerializedName("email") val email : String,
    @SerializedName("first_name") val first_name : String,
    @SerializedName("last_name") val last_name : String,
    @SerializedName("avatar") val avatar : String
)

Update the activity_main.xml

Now in main_activity has below layout, So we have a RecyclerView, then TextView in case of error, we can display a message. And we have a ProgressBar, so user know that is something is going in background. So its quite simple you know. So there are 3 element and we’re going to hide to show these element.

<?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=".view.MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/usersList"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/listError"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:gravity="center"
        tools:text="Error"
        android:textColor="#FA1302"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ProgressBar
        android:id="@+id/loadingView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout> 

Create a ViewModel

Let create a ViewModel named is ListViewModel. Here we simply fetching user list from backend server and passes that data to our MutableLiveData. Apart from this, we have a load error which generates an error message in case of API failure. and we have a loading MutableLiveData(), That let us know there is something happens in background.

package com.retrofitcoroutines.example.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.retrofitcoroutines.example.model.User
import com.retrofitcoroutines.example.remote.UserService
import kotlinx.coroutines.*

class ListViewModel : ViewModel() {

    val userService = UserService().getUsersService()
    var job: Job? = null
    val exceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
        onError("Exception handled: ${throwable.localizedMessage}")
    }

    val users = MutableLiveData<List<User>>()
    val usersLoadError = MutableLiveData<String?>()
    val loading = MutableLiveData<Boolean>()

    fun refresh() {
        fetchUsers()
    }

    private fun fetchUsers() {
        loading.value = true
        job = CoroutineScope(Dispatchers.IO + exceptionHandler).launch {
            val response = userService.getUsers()
            withContext(Dispatchers.Main) {
                if (response.isSuccessful) {
                    users.value = response.body()?.data
                    usersLoadError.value = null
                    loading.value = false
                } else {
                    onError("Error : ${response.message()} ")
                }
            }
        }
        usersLoadError.value = ""
        loading.value = false
    }

    private fun onError(message: String) {
        usersLoadError.value = message
        loading.value = false
    }

    override fun onCleared() {
        super.onCleared()
        job?.cancel()
    }

} 

Connect ListViewModel to MainActivity

In the MainActivity we are instantiating the ListViewModel. Then we simply set up our RecycleView, Using a UserAdapter, That we’ll create below of the code, and then we are observing the ViewModel, which simply connecting Livedata from the ViewModel and proceeding to update the interface based on the information that we received. So all is that we need to do.

package com.retrofitcoroutines.example.view

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.retrofitcoroutines.example.R
import com.retrofitcoroutines.example.viewmodel.ListViewModel
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    lateinit var viewModel: ListViewModel
    private val userListAdapter = UserListAdapter(arrayListOf())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        viewModel = ViewModelProviders.of(this).get(ListViewModel::class.java)
        viewModel.refresh()

        usersList.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = userListAdapter
        }

        observeViewModel()
    }
    private fun observeViewModel() {
        viewModel.users.observe(this, Observer {countries ->
            countries?.let {
                usersList.visibility = View.VISIBLE
                userListAdapter.updateCountries(it) }
        })

        viewModel.usersLoadError.observe(this, Observer { isError ->
            listError.visibility = if(isError == "") View.GONE else View.VISIBLE
        })

        viewModel.loading.observe(this, Observer { isLoading ->
            isLoading?.let {
                loadingView.visibility = if(it) View.VISIBLE else View.GONE
                if(it) {
                    listError.visibility = View.GONE
                    usersList.visibility = View.GONE
                }
            }
        })
    }
}

Now create UserListAdapter

Simply create a RecyclerView Adapter and attached the user_item view to recycler as usual. The only different thing here is the extension function for ImageView to load the image which allows us to loan an image on ImageView based on the URL we have.

package com.retrofitcoroutines.example.view

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.retrofitcoroutines.example.R
import com.retrofitcoroutines.example.model.User
import com.retrofitcoroutines.example.utils.loadImage
import kotlinx.android.synthetic.main.item_user.view.*

class UserListAdapter(var users: ArrayList<User>): RecyclerView.Adapter<UserListAdapter.UserViewHolder>() {

    fun updateCountries(newUsers: List<User>) {
        users.clear()
        users.addAll(newUsers)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, p1: Int) = UserViewHolder(
        LayoutInflater.from(parent.context).inflate(R.layout.item_user, parent, false)
    )

    override fun getItemCount() = users.size

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        holder.bind(users[position])
    }

    class UserViewHolder(view: View): RecyclerView.ViewHolder(view) {

        private val imageView = view.userAvatar
        private val userName = view.userFullName
        private val userEmail = view.userEmail


        fun bind(user: User) {
            userName.text = user.first_name + " "+ user.last_name
            userEmail.text = user.email
            imageView.loadImage(user.avatar)
        }
    }
}

Here is item_user.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="wrap_content"
    android:layout_margin="8dp"
    android:background="#E4DDF3">

    <ImageView
        android:id="@+id/userAvatar"
        android:layout_width="80dp"
        android:layout_height="80dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/userFullName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/userAvatar"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Morris" />

    <TextView
        android:id="@+id/userEmail"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        tools:text="morris@androidwave.com"
        android:textSize="16sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/userAvatar"
        app:layout_constraintTop_toBottomOf="@+id/userFullName" />
</androidx.constraintlayout.widget.ConstraintLayout>

Write a extension function for ImageView

Here I have created a new package named is utils and writes below extension function.

package com.retrofitcoroutines.example.utils

import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.retrofitcoroutines.example.R

fun ImageView.loadImage(uri: String?) {
    val options = RequestOptions()
        .error(R.mipmap.ic_launcher_round)
    Glide.with(this.context)
        .setDefaultRequestOptions(options)
        .load(uri)
        .into(this)
}
  

That all about UI let setup Retrofit and connect it with project.

Setting up Retrofit

Let create a retrofit interface. Here I’m gonna set up a GET function for Retrofit. Inside this interface create a suspending function like below. It simply returns us a Response.

package com.retrofitcoroutines.example.remote

import com.retrofitcoroutines.example.model.UserList
import retrofit2.Response
import retrofit2.http.GET

interface UserApi {

    @GET("users")
    suspend fun getUsers(): Response<UserList>

} 

Create a UsersService

In this class, first of I have created a variable here is BASE_URL. After that I have created a function named is getUsersService() that simply returns UserApi that we just defined earlier.

package com.retrofitcoroutines.example.remote

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class UserService {
    
    private val BASE_URL = "https://reqres.in/api/";
    fun getUsersService(): UserApi{
       return Retrofit.Builder()
           .baseUrl(BASE_URL)
           .addConverterFactory(GsonConverterFactory.create())
           .build()
           .create(UserApi::class.java)
    }
}

That all done, let’s go ahead and run the code and see if it works. It’s working so we have all users that return from APIs in the context of coroutines. Basically, in this example, we have two coroutines because first, we are calling with Dispatchers.IO and finally we are calling Dispatchers.Main. So way we can update UI in main. thread. That code I already added in ViewModel, for reference I adding again

CoroutineScope(Dispatchers.IO + exceptionHandler).launch {
            val response = userService.getUsers()
            withContext(Dispatchers.Main) {
                if (response.isSuccessful) {
                    users.value = response.body()?.data
                    usersLoadError.value = null
                    loading.value = false
                } else {
                    onError("Error : ${response.message()} ")
                }
            }
        } 

Conclusion

So that is it, So we learned how to use Retrofit with coroutines in Kotlin| Android.  I hope it’s helpful for you, Help me by sharing this post with all your friends who learning android app development.

Download Source Code

Retrofit coroutines error handling

will publish a complete article on that, For now you can follow this article

Retrofit with coroutines

This is a sample app thats created. Please follow this article only

Hello folks! In this article, We’ll learn the best practices of SharedPreferences in Android(Kotlin). I’ll show you, how we can store and retrieve values in SharedPreferences. For better understanding, I’ll create an android SharedPreferences example (Sample app) and take an example of Writing and Reading Values in SharedPreferences. So let started

What are SharePreferences?

SharedPreferences is an android API that stores app data using key-value pairs and provides simple methods to read and write them.

Android system provides several options for you to save your data. These options are App-specific storage, Shared storage, Preferences, Databases. SharePreferences comes in Preference. It offers a framework to save private, primitive data in key-value pairs.

Why SharePreferences?

They’re mostly used to store user states when it comes to user settings or keeps a piece of small information(User details etc.) without needing storage permission. As per my opinion, you should store small primitive value in Preferences such as booleans, ints, longs, floats, and strings.

Modes in SharePreferences

SharedPreferences have different MODE these are below

1. Create a android application

Let take an example, open android studio, and create a new project. Now create a interface named is IPreferenceHelper. In this Interface we are defining some getter setter for storing or retrieving preference value. such as ApiKey and UserId etc.

package com.sharedpreferencesexample

interface IPreferenceHelper {

    fun setApiKey(apiKey: String)

    fun getApiKey(): String

    fun setUserId(userId: String)

    fun getUserId(): String

    fun clearPrefs()

}

2. Create a singleton class for managing Preferences

Ideally SharedPreferences store the app level value, So the SharedPreferences instance should be single threw out the app. It should be a singleton. Let create a Singletone class named is PreferenceManager and implement IPreferenceHelper. Just like below

open class PreferenceManager constructor(context: Context) : IPreferenceHelper {
    private val PREFS_NAME = "SharedPreferenceDemo"
    private var preferences: SharedPreferences

    init {
        preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    }

    override fun setApiKey(apiKey: String) {
        preferences[API_KEY] = apiKey
    }

    override fun getApiKey(): String {
        return preferences[API_KEY] ?: ""
    }

    override fun setUserId(userId: String) {
        preferences[USER_ID] = userId
    }

    override fun getUserId(): String {
        return preferences[USER_ID] ?: ""
    }

    override fun clearPrefs() {
        preferences.edit().clear().apply()
    }

    companion object {
        const val API_KEY = "api_key"
        const val USER_ID = "user_id"
    }
}

3. Write into your SharedPreferences

Normally, writing into SharedPreferences is simple. But I’m going to write a Kotlin extension, This extension is make writing very simple and reduce boilerplate code.

/**
 * SharedPreferences extension function, to listen the edit() and apply() fun calls
 * on every SharedPreferences operation.
 */
private inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
    val editor = this.edit()
    operation(editor)
    editor.apply()
}

/**
 * puts a key value pair in shared prefs if doesn't exists, otherwise updates value on given [key]
 */
private operator fun SharedPreferences.set(key: String, value: Any?) {
    when (value) {
        is String? -> edit { it.putString(key, value) }
        is Int -> edit { it.putInt(key, value) }
        is Boolean -> edit { it.putBoolean(key, value) }
        is Float -> edit { it.putFloat(key, value) }
        is Long -> edit { it.putLong(key, value) }
        else -> throw UnsupportedOperationException("Not yet implemented")
    }
}

4.  Read from SharedPreferences

Reading a value from SharedPreferences is also straightforward. I’m going to write another useful extension that provides more control over retrieving a value from SharedPreferences. Let check below code

/**
 * finds value on given key.
 * [T] is the type of value
 * @param defaultValue optional default value - will take null for strings, false for bool and -1 for numeric values if [defaultValue] is not specified
 */
private inline operator fun <reified T : Any> SharedPreferences.get(
    key: String,
    defaultValue: T? = null
): T? {
    return when (T::class) {
        String::class -> getString(key, defaultValue as? String) as T?
        Int::class -> getInt(key, defaultValue as? Int ?: -1) as T?
        Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T?
        Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T?
        Long::class -> getLong(key, defaultValue as? Long ?: -1) as T?
        else -> throw UnsupportedOperationException("Not yet implemented")
    }
}

5. Finally your PreferenceManager class look like below

package com.sharedpreferencesexample

import android.content.Context
import android.content.SharedPreferences

open class PreferenceManager constructor(context: Context) : IPreferenceHelper {
    private val PREFS_NAME = "SharedPreferenceDemo"
    private var preferences: SharedPreferences

    init {
        preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    }

    override fun setApiKey(apiKey: String) {
        preferences[API_KEY] = apiKey
    }

    override fun getApiKey(): String {
        return preferences[API_KEY] ?: ""
    }

    override fun setUserId(userId: String) {
        preferences[USER_ID] = userId
    }

    override fun getUserId(): String {
        return preferences[USER_ID] ?: ""
    }

    override fun clearPrefs() {
        preferences.edit().clear().apply()
    }

    companion object {
        const val API_KEY = "api_key"
        const val USER_ID = "user_id"
    }
}


/**
 * SharedPreferences extension function, to listen the edit() and apply() fun calls
 * on every SharedPreferences operation.
 */
private inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
    val editor = this.edit()
    operation(editor)
    editor.apply()
}

/**
 * puts a key value pair in shared prefs if doesn't exists, otherwise updates value on given [key]
 */
private operator fun SharedPreferences.set(key: String, value: Any?) {
    when (value) {
        is String? -> edit { it.putString(key, value) }
        is Int -> edit { it.putInt(key, value) }
        is Boolean -> edit { it.putBoolean(key, value) }
        is Float -> edit { it.putFloat(key, value) }
        is Long -> edit { it.putLong(key, value) }
        else -> throw UnsupportedOperationException("Not yet implemented")
    }
}

/**
 * finds value on given key.
 * [T] is the type of value
 * @param defaultValue optional default value - will take null for strings, false for bool and -1 for numeric values if [defaultValue] is not specified
 */
private inline operator fun <reified T : Any> SharedPreferences.get(
    key: String,
    defaultValue: T? = null
): T? {
    return when (T::class) {
        String::class -> getString(key, defaultValue as? String) as T?
        Int::class -> getInt(key, defaultValue as? Int ?: -1) as T?
        Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T?
        Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T?
        Long::class -> getLong(key, defaultValue as? Long ?: -1) as T?
        else -> throw UnsupportedOperationException("Not yet implemented")
    }
}

6. Access PreferenceManager into your presentation layers

Yes, Now your PreferenceManager class is ready for use. You can initialize PreferenceManager class into your ViewModel and Activity/Fragment, Make sure the context should be applicationContext.

7. Now open the activity_main.xml and paste below code.

For making interesting example I have added two edit text and one button in this layout

<?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:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Hello World!" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="User Id"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="API Key"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Show Preference Data"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

</androidx.constraintlayout.widget.ConstraintLayout>

8. Let access PreferenceManager class in your source file

Let’s check the below code This way you can easily read and write the value in SharePreferences

package com.sharedpreferencesexample

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private val preferenceHelper: IPreferenceHelper by lazy { PreferenceManager(applicationContext) }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // display saved data
        textView.text =
            " API Key - > ${preferenceHelper.getApiKey()} \n User Id -> ${preferenceHelper.getUserId()}"
        button.setOnClickListener {
            // Update data in SharedPreference
            preferenceHelper.setApiKey(editText.text.toString())
            preferenceHelper.setUserId(editText2.text.toString())
            // display saved data
            textView.text =
                " API Key - > ${preferenceHelper.getApiKey()} \n User Id -> ${preferenceHelper.getUserId()}"
        }

    }
}

7. Build & Test

Let run the app, in a movement your app will up and run, Now enter few value these EditText and click button. The value will display on TextView. This way you can read and write small amount of data in key-value pairs!

Conclusion

In this android SharedPreferences example, we’ll learn how we can save and retrieve value in SharedPreferences. I try to follow best practices for android development. Still, you want to improve… Most Welcome

Follow this article to detect network change in Android!

In this blog, I’ll show how to check internet connection in android programmatically. While we are developing a professional app, you may need to check internet available or not. For example, while you are calling APIs you may need to check internet connection several times in an app. In this example, we’ll learn how we can check internet connections any place and anywhere.

I’m going to create a demo application, This app will automatically detect the internet changes using an internet connection listener. For the demonstration, I’ll create a sample app that app will capable of continuously check internet connection with android. So let started.

Create Android Project

Let move to Android Studio, and create a fresh project with some default template. We are going to use java 1.8 stuff in our project so lets set java version in app build.gradle file

  compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }  

Add ACCESS_NETWORK_STATE permission in Manifest

For detecting network permission we required some permission so let open the AndroidManifest and add below permission.

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

Write a ConnectivityProvider interface

I’m going to write complete solution for check internet connection for pre and post LOLLIPOP devices solution in a single interface. Please have a look

package com.detectnetworkchange.connectivity.base

import android.content.Context
import android.content.Context.CONNECTIVITY_SERVICE
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET
import android.net.NetworkInfo
import android.os.Build
import androidx.annotation.RequiresApi
import com.detectnetworkchange.connectivity.ConnectivityProviderImpl
import com.detectnetworkchange.connectivity.ConnectivityProviderLegacyImpl

interface ConnectivityProvider {

    fun subscribe()

    fun getNetworkState(): NetworkState

    @Suppress("MemberVisibilityCanBePrivate", "CanBeParameter")
    sealed class NetworkState {
        object NotConnectedState : NetworkState()

        sealed class ConnectedState(val hasInternet: Boolean) : NetworkState() {

            @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
            data class Connected(val capabilities: NetworkCapabilities) : ConnectedState(
                    capabilities.hasCapability(NET_CAPABILITY_INTERNET)
            )

            @Suppress("DEPRECATION")
            data class ConnectedLegacy(val networkInfo: NetworkInfo) : ConnectedState(
                    networkInfo.isConnectedOrConnecting
            )
        }
    }

    companion object {
        @JvmStatic
        fun createProvider(context: Context): ConnectivityProvider {
            val cm = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                ConnectivityProviderImpl(cm)
            } else {
                ConnectivityProviderLegacyImpl(context, cm)
            }
        }
    }
}

Extend ConnectivityProvider interface

Now create a abstract class named ConnectivityProviderBaseImpl which extends ConnectivityProvider interface, like below

package com.detectnetworkchange.connectivity.base

import com.detectnetworkchange.CONNECTED
import com.detectnetworkchange.DISCONNECTED
import com.detectnetworkchange.NetWorkManger
import com.detectnetworkchange.connectivity.base.ConnectivityProvider.NetworkState

abstract class ConnectivityProviderBaseImpl : ConnectivityProvider {
    override fun subscribe() {
        subscribeListener()
        //init status
        dispatchChange(getNetworkState())
    }

    protected fun dispatchChange(state: NetworkState) {
        val networkState = if (state.hasInternet()) CONNECTED else DISCONNECTED
        if (networkState != NetWorkManger.networkStatus.value) {
            NetWorkManger.networkStatus.postValue(networkState)
        }
    }

    private fun NetworkState.hasInternet(): Boolean {
        return (this as? NetworkState.ConnectedState)?.hasInternet == true
    }

    protected abstract fun subscribeListener()
}

Write a actual implementation of ConnectivityProvider

package com.detectnetworkchange.connectivity

import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import androidx.annotation.RequiresApi
import com.detectnetworkchange.connectivity.base.ConnectivityProvider.NetworkState
import com.detectnetworkchange.connectivity.base.ConnectivityProvider.NetworkState.ConnectedState.Connected
import com.detectnetworkchange.connectivity.base.ConnectivityProvider.NetworkState.NotConnectedState
import com.detectnetworkchange.connectivity.base.ConnectivityProviderBaseImpl

@RequiresApi(Build.VERSION_CODES.N)
class ConnectivityProviderImpl(private val cm: ConnectivityManager) :
        ConnectivityProviderBaseImpl() {

    private val networkCallback = ConnectivityCallback()

    override fun subscribeListener() {
        cm.registerDefaultNetworkCallback(networkCallback)
    }

    override fun getNetworkState(): NetworkState {
        val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
        return if (capabilities != null) {
            Connected(capabilities)
        } else {
            NotConnectedState
        }
    }

    private inner class ConnectivityCallback : NetworkCallback() {

        override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
            dispatchChange(Connected(capabilities))
        }

        override fun onLost(network: Network) {
            dispatchChange(NotConnectedState)
        }
    }
}
package com.detectnetworkchange.connectivity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.ConnectivityManager.CONNECTIVITY_ACTION
import android.net.ConnectivityManager.EXTRA_NETWORK_INFO
import android.net.NetworkInfo
import com.detectnetworkchange.connectivity.base.ConnectivityProvider.NetworkState
import com.detectnetworkchange.connectivity.base.ConnectivityProvider.NetworkState.ConnectedState.ConnectedLegacy
import com.detectnetworkchange.connectivity.base.ConnectivityProvider.NetworkState.NotConnectedState
import com.detectnetworkchange.connectivity.base.ConnectivityProviderBaseImpl

@Suppress("DEPRECATION")
class ConnectivityProviderLegacyImpl(
        private val context: Context,
        private val cm: ConnectivityManager
) : ConnectivityProviderBaseImpl() {

    private val receiver = ConnectivityReceiver()

    override fun subscribeListener() {
        context.registerReceiver(receiver, IntentFilter(CONNECTIVITY_ACTION))
    }

    override fun getNetworkState(): NetworkState {
        val activeNetworkInfo = cm.activeNetworkInfo
        return if (activeNetworkInfo != null) {
            ConnectedLegacy(activeNetworkInfo)
        } else {
            NotConnectedState
        }
    }

    private inner class ConnectivityReceiver : BroadcastReceiver() {
        override fun onReceive(c: Context, intent: Intent) {
            // on some devices ConnectivityManager.getActiveNetworkInfo() does not provide the correct network state
            val networkInfo = cm.activeNetworkInfo
            val fallbackNetworkInfo: NetworkInfo? = intent.getParcelableExtra(EXTRA_NETWORK_INFO)
            // a set of dirty workarounds
            val state: NetworkState =
                    if (networkInfo?.isConnectedOrConnecting == true) {
                        ConnectedLegacy(networkInfo)
                    } else if (networkInfo != null && fallbackNetworkInfo != null &&
                            networkInfo.isConnectedOrConnecting != fallbackNetworkInfo.isConnectedOrConnecting
                    ) {
                        ConnectedLegacy(fallbackNetworkInfo)
                    } else {
                        val state = networkInfo ?: fallbackNetworkInfo
                        if (state != null) ConnectedLegacy(state) else NotConnectedState
                    }
            dispatchChange(state)
        }
    }
}

Let’s create a NetWorkManger class

In this class we have one live data object which hold the internet state, It can be accessible threw out the application.

package com.detectnetworkchange

import androidx.lifecycle.MutableLiveData


const val DISCONNECTED = 0
const val CONNECTED = 1

object NetWorkManger {
    val networkStatus = MutableLiveData<Int>()

    fun isDisconnected(): Boolean {
        return networkStatus.value == DISCONNECTED
    }
}

class NetWorkDisconnectedException : Throwable()

Finally subscribe the ConnectivityProvider instance in application class

package com.detectnetworkchange

import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Process
import com.detectnetworkchange.connectivity.base.ConnectivityProvider

class DetectNetworkChangeDemoApp : Application() {
    override fun onCreate() {
        super.onCreate()
        if (isMainProcess()) {
            ConnectivityProvider.createProvider(this).subscribe()
        }
    }

    // your package name is the same with your main process name
    private fun isMainProcess(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            packageName == getProcessName()
        } else packageName == getProcessNameLegacy()
    }

    // you can use this method to get current process name, you will get
    private fun getProcessNameLegacy(): String? {
        val mypid = Process.myPid()
        val manager =
            getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val infos = manager.runningAppProcesses
        for (info in infos) {
            if (info.pid == mypid) {
                return info.processName
            }
        }
        // may never return null
        return null
    }
}

This way you can observe network changes

package com.detectnetworkchange

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Suppose you want to check network status before calling APIs then use this way
        Log.d("MainActivity","Network connected "+!NetWorkManger.isDisconnected())
        // if you want observe network status then use this way
        NetWorkManger.networkStatus.observe(this, Observer {
            when (it) {
                CONNECTED -> status.text ="Internet is connected"
                DISCONNECTED -> status.text ="Internet disconnected"
            }
        })


    }
}

In this post, I’ll show you how we can write double tap listener in android. For doing that I’ll create one demo project and will implement it. So Lets started

Write a DoubleClickListener

Create an abstract class named is DoubleClickListener which extends native View.OnClickListener. Technically nothing we are doing. Simply observe the normal click If the second click happens with delta time then we triggered onDoubleClick event. Just like below

package com.doubletaplistener

import android.view.View

abstract class DoubleClickListener : View.OnClickListener {
    private var lastClickTime: Long = 0
    override fun onClick(v: View) {
        val clickTime = System.currentTimeMillis()
        if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
            onDoubleClick(v)
            lastClickTime = 0
        }
        lastClickTime = clickTime
    }

    abstract fun onDoubleClick(v: View)

    companion object {
        private const val DOUBLE_CLICK_TIME_DELTA: Long = 300 //milliseconds
    }
}

Lets come to the implementation

For implementation double tap listener just create an android sample project. You can apply double click listener is anywhere. In this demo, I’m taking one button. On this button, I will set double click listener, for verifying this I’ll show the toast.

package com.doubletaplistener

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // handle double tap event
        doubleTap.setOnClickListener(object : DoubleClickListener() {
            override fun onDoubleClick(v: View) {
               Toast.makeText(applicationContext,"Double Clicked Attempts",Toast.LENGTH_SHORT).show()
            }
        })
    }
}

Conclusion

In this android app Example, I show you Double Tap Listener Android Example. I hope it’s helpful for you, then help me by sharing this post with all your friends who learning android app development.

Read our new article on Kotlin String Template

In this article, I’ll show how we can send an FCM message from an android device. in other words, you can say, will tell send android firebase push notifications device to device. How to do that, Let’s get started.

Create a new application.

Let’s open the Android Studio and create a new project with the default template.

Add libraries in app-level build.gradle file

In this example, we are using followings libraries for making network call

  //  Add these line in your project
  implementation 'com.squareup.retrofit2:retrofit:2.7.1'
  implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
  implementation 'com.squareup.retrofit2:adapter-rxjava2:2.7.1'
  implementation "com.squareup.okhttp3:logging-interceptor:4.3.1"
Add Base URL and FCM SERVER KEY in build config field your project build.gradle

Let add below variables inside gradle file. Now create a project on firebase. After that Replace FCM_SERVER_KEY ID with your server id.

buildTypes {
    debug {
      buildConfigField("String", "FCM_BASE_URL", "\"https://fcm.googleapis.com/\"")
      buildConfigField("String", "FCM_SERVER_KEY", "\"xxxxxxxxxxxxxxxxxxxxxxxx\"")
    }
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
  }
Add Internet permission manifest

For sending the notification, we will need to internet permission, let’s open the android manifest and add below permission.

  <uses-permission android:name="android.permission.INTERNET" />
Write a network API client

Let’s create a network provider class, In this class, we are using Retrofit and OKHHTP client for debugging.

package com.sendinganotificationmessage;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
  public static NotificationApiService getApiService() {
    return new Retrofit.Builder()
        .baseUrl(BuildConfig.FCM_BASE_URL)
        .client(provideClient())
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(NotificationApiService.class);
  }

  private static OkHttpClient provideClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return new OkHttpClient.Builder().addInterceptor(interceptor).addInterceptor(chain -> {
      Request request = chain.request();
      return chain.proceed(request);
    }).build();
  }
}
Now create notification API service
package com.sendinganotificationmessage;

import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public interface NotificationApiService {

  @Headers({
      "Authorization: key="+BuildConfig.FCM_SERVER_KEY ,
      "Content-Type: application/json"
  })
  @POST("fcm/send")
  Call<JsonObject> sendNotification(@Body JsonObject payload);
}
Modify your main activity layout file

For taking input from the user will update the layout file that contains a few text input item for capturing device token, title and message

<?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=".MainActivity"
    >

  <com.google.android.material.textfield.TextInputLayout
      android:id="@+id/textInputLayout5"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginStart="16dp"
      android:layout_marginTop="16dp"
      android:layout_marginEnd="16dp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      >

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/textReceiverToken"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Receiver FCM Token"
        android:maxLines="1"
        android:text="fnn3DoqhPPM:APA91bHBDfHv0YC5Mpncu1Got_d28-FIRDEH1gwXj27HGB5_Qbn49cyE7M2zeKijq4FEuApsW6-lEbNGrIGwhhERKTTtGxLvz8Q5xvF_x1QlX3Um8DiKsnYjqeEMySrjAhQNeI8Kot7S"

        />
  </com.google.android.material.textfield.TextInputLayout>
  <com.google.android.material.textfield.TextInputLayout
      android:id="@+id/textInputLayout"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginStart="16dp"
      android:layout_marginTop="8dp"
      android:layout_marginEnd="16dp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/textInputLayout5"
      >

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/textTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Title"
        />
  </com.google.android.material.textfield.TextInputLayout>
  <com.google.android.material.textfield.TextInputLayout
      android:id="@+id/textInputLayout2"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginStart="16dp"
      android:layout_marginTop="8dp"
      android:layout_marginEnd="16dp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/textInputLayout"
      >

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/textMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Message"/>
  </com.google.android.material.textfield.TextInputLayout>
  <TextView
      android:id="@+id/textView"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginStart="16dp"
      android:layout_marginTop="16dp"
      android:text="Additional data you want to pass (In key-value pair)"
      android:textColor="@color/colorAccent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/textInputLayout2"
      />
  <com.google.android.material.textfield.TextInputLayout
      android:id="@+id/textInputLayout3"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginStart="16dp"
      android:layout_marginTop="16dp"
      app:layout_constraintEnd_toStartOf="@+id/textInputLayout4"
      app:layout_constraintHorizontal_bias="0.5"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/textView"
      >

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/textKey"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Key"
        />
  </com.google.android.material.textfield.TextInputLayout>
  <com.google.android.material.textfield.TextInputLayout
      android:id="@+id/textInputLayout4"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginStart="16dp"
      android:layout_marginEnd="16dp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintHorizontal_bias="0.5"
      app:layout_constraintStart_toEndOf="@+id/textInputLayout3"
      app:layout_constraintTop_toTopOf="@+id/textInputLayout3"
      >

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/textValue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Value"
        />
  </com.google.android.material.textfield.TextInputLayout>
  <Button
      android:id="@+id/buttonSendNotification"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginStart="16dp"
      android:layout_marginTop="24dp"
      android:layout_marginEnd="16dp"
      android:background="@color/colorAccent"
      android:text="Send Notification"
      android:textColor="#ffffff"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/textInputLayout3"
      />


</androidx.constraintlayout.widget.ConstraintLayout>
Let’s move to main activity files

Let’s bind the views using id. As you see below code we taking the input from users and send notification using the retrofit client. We taking input like title, messaging and FCM token.

package com.sendinganotificationmessage;

import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputEditText;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
  Button sendNotificationButton;
  TextInputEditText receiverFdmId;
  TextInputEditText title;
  TextInputEditText message;
  TextInputEditText key;
  TextInputEditText value;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initViews();
    sendNotificationButton.setOnClickListener(view -> {
      if (validateInput()) {
        JsonObject payload = buildNotificationPayload();
        // send notification to receiver ID
        ApiClient.getApiService().sendNotification(payload).enqueue(
            new Callback<JsonObject>() {
              @Override
              public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                if (response.isSuccessful()) {
                  Toast.makeText(MainActivity.this, "Notification send successful",
                      Toast.LENGTH_LONG).show();
                }
              }

              @Override public void onFailure(Call<JsonObject> call, Throwable t) {

              }
            });
      }
    });
  }

  private JsonObject buildNotificationPayload() {
    // compose notification json payload
    JsonObject payload = new JsonObject();
    payload.addProperty("to", receiverFdmId.getText().toString());

    // compose data payload here
    JsonObject data = new JsonObject();
    data.addProperty("title", title.getText().toString());
    data.addProperty("message", message.getText().toString());
    data.addProperty(key.getText().toString(), value.getText().toString());
    // add data payload
    payload.add("data", data);
    return payload;
  }

  private boolean validateInput() {
    if (receiverFdmId.getText().toString().isEmpty()
        || title.getText().toString().isEmpty()
        || message.getText().toString().isEmpty()
        || key.getText().toString().isEmpty()
        || value.getText().toString().isEmpty()) {
      Toast.makeText(this, "Please fill all field correctly", Toast.LENGTH_LONG).show();
      return false;
    }
    return true;
  }

  private void initViews() {
    sendNotificationButton = findViewById(R.id.buttonSendNotification);
    receiverFdmId = findViewById(R.id.textReceiverToken);
    title = findViewById(R.id.textTitle);
    message = findViewById(R.id.textMessage);
    key = findViewById(R.id.textKey);
    value = findViewById(R.id.textValue);
  }
}

Let’s run the project and see your app will run and up. Lets put device token, title and message, finally tap on send.

Conclusion

In this android app tutorial, We have learned the implementation of sending FCM message from android. I hope it’s helpful for you, let’s do a favor for me, share this post with all your friends.

Get Solution Code

Keep in touch

If you want to keep in touch so let’s follow me on Facebook or Subscribe to us. Still, if you have any queries please put your comment below.

I this post, will learn about firebase cloud messaging in android. I will show you a full demonstration with sample app. Let see how we setup firebase cloud messaging in our app

Overview
  • Firebase Cloud Messaging is a cross-platform messaging solution that lets you reliably deliver messages free of cost.
  • It just allows you to notify a client that a new email, data or other data is available to sync.
  • You can send notification messages that are displayed to the user.
  • Notification messaging is act as instant messaging. A message can transfer a payload of up to 4KB to the client.
  • You can send a message to a single device, group of the device, or to devices subscribed to topic.
Implementation step of firebase cloud messaging in your app
  • Create an android project
  • Create a firebase project on firebase console
  • Connect your app to firebase
  • Setup your android app to use the cloud messaging libraries
  • Receive the code when the app is background and foreground.
Setup your android app to use the cloud messaging libraries

Navigate your project, In project-level build.gradle file make sure to include Google maven.

build.gradle (project-level)
    // add these line
    classpath 'com.google.gms:google-services:4.2.0'
app/build.gradle
  //  Add these line
  implementation 'com.google.firebase:firebase-messaging:20.1.0'
  implementation 'android.arch.work:work-runtime:1.0.1'
Add this line on top of app/build.gradle
apply plugin: 'com.google.gms.google-services'
Add internet uses permission
  <uses-permission android:name="android.permission.INTERNET" />
Set Notification custom icon as default in manifest
    <! – Add these line -->
    <! – [START] -->
    <! – Set custom default icon -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_notification" />
    <! – Set color used with incoming notification messages. This is used when no color is set for the incoming notification message.-->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />
    <! –  Set fcm default channel-->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/default_notification_channel_id" />
    <! – [END] -->

Let’s create a service class named is CloudMessagingService

In the src folder create a service class named CloudMessagingService which extends FirebaseMessagingService. We have to override two methods which are onNewToken() and onMessageReceived().

Let’s override onNewToken methods.

In this methods make own server request here using your HTTP client

  @Override
  public void onNewToken(String token) {
    super.onNewToken(token);
    Log.d(TAG, "Refreshed token: " + token);
    // make a own server request here using your http client
  }
Now override onMessageReceived method

Let’s override onMessageReceived method, in this method we received RemoteMessgage instance that contains all message details.

Message Type

Firebase cloud messing allow you to send two types of messages.

  • Notification Messages
    • It displays the notification. It’s managed by firebase SDK, FCM automatically to the end-user device on behalf of the client app.
    • Notification messages contain a predefined set of user-visible keys.
  • Data Messages
    • Data messages contain only your user defines custom key-value pair.
    • Handled by the app itself. It contains key-value pairs, based on this you can do something(such as make some event, store some data, sync some data ).

The maximum payload of both messages type is 4 KB, except when sending messaging from firebase console, which enforces a 1024 character limit.

Check Notification Messages

Check remote message contains a notification payload or not.

 // if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
      Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }
Handle DATA messages

Check remote message contains a data payload. If data payload contains more than 10 seconds job then we should run log run job using WorkManager. If the task is within 10 min then we should handle it.

  //  if remote message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
      Log.d(TAG, "Message data payload: " + remoteMessage.getData());
      Map<String, String> data = remoteMessage.getData();

      String jobType = data.get("type");
     /* Check the message contains data If needs to be processed by long running job
         so check if data needs to be processed by long running job */

      if (jobType.equalsIgnoreCase(JobType.LONG.name())) {
        // For long-running tasks (10 seconds or more) use WorkManager.
        scheduleLongRunningJob();
      } else {
        // Handle message within 10 seconds
        handleNow(data);
      }
    }
Create and show notification containing the received FCM message.
private void sendNotification(String title, String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
        PendingIntent.FLAG_ONE_SHOT);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
        new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      // Channel human readable title
      NotificationChannel channel = new NotificationChannel(channelId,
          "Cloud Messaging Service",
          NotificationManager.IMPORTANCE_DEFAULT);
      notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
  }
Finally, your CloudMessagingService class looks like this.
package com.firebasecloudmessaging;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.Map;

public class CloudMessagingService extends FirebaseMessagingService {
  private static final String TAG = "CloudMessagingService";

  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    // log the getting message from firebase
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    //  if remote message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
      Log.d(TAG, "Message data payload: " + remoteMessage.getData());
      Map<String, String> data = remoteMessage.getData();

      String jobType = data.get("type");
     /* Check the message contains data If needs to be processed by long running job
         so check if data needs to be processed by long running job */

      if (jobType.equalsIgnoreCase(JobType.LONG.name())) {
        // For long-running tasks (10 seconds or more) use WorkManager.
        scheduleLongRunningJob();
      } else {
        // Handle message within 10 seconds
        handleNow(data);
      }
    }

    // if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
      Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }
  }

  @Override
  public void onNewToken(String token) {
    super.onNewToken(token);
    Log.d(TAG, "Refreshed token: " + token);
    sendRegistrationToServer(token);
  }

  /**
   * Persist token on third-party servers using your Retrofit APIs client.
   * Modify this method to associate the user's FCM InstanceID token with any server-side account
   *
   * @param token The new token.
   */
  private void sendRegistrationToServer(String token) {
    // make a own server request here using your http client

  }

  private void handleNow(Map<String, String> data) {
    if (data.containsKey("title") && data.containsKey("message")) {
      sendNotification(data.get("title"), data.get("message"));
    }
  }

  /**
   * Schedule async work using WorkManager mostly these are one type job.
   */
  private void scheduleLongRunningJob() {
    OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(DataSyncWorker.class)
        .build();
    WorkManager.getInstance().beginWith(work).enqueue();
  }

  /**
   * Create and show notification containing the received FCM message.
   *
   * @param messageBody FCM message body received.
   */
  private void sendNotification(String title, String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
        PendingIntent.FLAG_ONE_SHOT);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
        new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      // Channel human readable title
      NotificationChannel channel = new NotificationChannel(channelId,
          "Cloud Messaging Service",
          NotificationManager.IMPORTANCE_DEFAULT);
      notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
  }
}
Modify main activity layout file

This file I’m adding a button for logging firebase token.

<?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=".MainActivity"
    >


  <Button
      android:id="@+id/logTokenButton"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Log Token"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />
</androidx.constraintlayout.widget.ConstraintLayout>
Meanwhile, open the MainActivity, and manage followings things
  • Handle possible data accompanying notification message
  • Log and show the Get new Instance ID token
package com.firebasecloudmessaging;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;

public class MainActivity extends AppCompatActivity {
  private static final String TAG = "MainActivity";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // If a notification message is tapped, any data accompanying the notification
    // message is available in the intent extras.
    // Handle possible data accompanying notification message.
    if (getIntent().getExtras() != null) {
      for (String key : getIntent().getExtras().keySet()) {
        Object value = getIntent().getExtras().get(key);
        Log.d(TAG, "Key: " + key + " Value: " + value);
        // navigate the app based on param
      }
    }

    // Log and show the  Get new Instance ID token
    Button loginButton = findViewById(R.id.logTokenButton);
    loginButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(
            new OnCompleteListener<InstanceIdResult>() {
              @Override public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                  Log.e(TAG, "getInstanceId failed", task.getException());
                  return;
                }

                // Get new Instance ID token
                String token = task.getResult().getToken();

                Log.d(TAG, token);
                Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
              }
            });
      }
    });
  }
}
Conclusion

All done, now run the app and see your app is run and up. you able to see the token on toast and logcat as well. Now send the messaging from android another device. Let’s see your notification is visible on the screen.

In this post, we learned how to implement Firebase Cloud Messaging Android our application. I hope it’s helpful for you, Help me by sharing this post with all your friends who learning android app development.

Happy coding 🙂

In this blog, I will show how to auto read OTP in android with the help of SMS User Consent API. In our previous blog, we have learned Automatic SMS Verification Android using SMS Retriever API. But it has some difficulty for example

  • SMS should start with <#> tag,
  • SMS should end with application hash code, etc.

In this article, I’m going to show you the implementation auto-read OTP using SMS User Consent API. It is complements of SMS Retriever API. Using SMS User Consent API we can achieve auto read OTP by allowing an app to prompt the user to grant access to the content of a single SMS message. When the user gives consent, the app can access the entire message to automatically complete SMS verification.

auto read otp android user consent 1
auto read otp android user consent 2
auto read otp android user consent 3

Image source google developers website.

  • Start – The first thing you have to start is listening before sending the message or OTP to the server.
  • Prompt – When the user’s device receives the SMS message containing a one-time code, Google Play services display the contents of the message to the user and asks for consent to make that text available to your app.
  • Read Message – If the user consents, the entire SMS message is made available to your app.
Message Criteria

Google play services imposed the followings SMS criteria

  • It contains a one-time password– The should message contains a 4–10 character alphanumeric string with at least one number.
  • Contacts – The message was sent by a phone number that’s not in the user’s contacts.
  • Timing – The API will look for the One Time Code for a maximum time of 5 minutes.
1. Let’s create a new project in Android Studio

Open to an android studio and create a new project. That project we will implement auto read OTP features. So I’m adding few strings in strings.xml file that we will use this project.

<resources>
  <string name="app_name">SMS verification</string>
  <string name="send_otp">Send OTP</string>
  <string name="generate_otp">Generate OTP</string>
  <string name="received_message">Received Message</string>
  <string name="verify_otp">Verify OTP</string>
</resources>

We should add below dependencies in app-level build.gradle in your project.

    // add these lines in your app build.gradle
    implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation 'com.google.android.gms:play-services-auth-api-phone:17.1.0'
3. Listen to the incoming messages

The next step is to listen to incoming messaging. we can start listening for incoming messages using below method. We can add sender phone number, SMS User Consent API will only trigger on messages from this number. I’m adding null here

  private void startSmsUserConsent() {
    SmsRetrieverClient client = SmsRetriever.getClient(this);
    //We can add sender phone number or leave it blank
    // I'm adding null here
    client.startSmsUserConsent(null).addOnSuccessListener(new OnSuccessListener<Void>() {
      @Override
      public void onSuccess(Void aVoid) {
        Toast.makeText(getApplicationContext(), "On Success", Toast.LENGTH_LONG).show();
      }
    }).addOnFailureListener(new OnFailureListener() {
      @Override
      public void onFailure(@NonNull Exception e) {
        Toast.makeText(getApplicationContext(), "On OnFailure", Toast.LENGTH_LONG).show();
      }
    });
  }
4. Create a BroadcastReceiver named is SmsBroadcastReceiver

In SmsBroadcastReceiverListener we will catch SMS and set back using SmsBroadcastReceiverListener callback methods.

package com.smsverification;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.gms.auth.api.phone.SmsRetriever;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.Status;

public class SmsBroadcastReceiver extends BroadcastReceiver{

  SmsBroadcastReceiverListener smsBroadcastReceiverListener;

  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction() == SmsRetriever.SMS_RETRIEVED_ACTION) {
      Bundle extras = intent.getExtras();
      Status smsRetrieverStatus = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
      switch (smsRetrieverStatus.getStatusCode()) {
        case CommonStatusCodes.SUCCESS:
          Intent messageIntent = extras.getParcelable(SmsRetriever.EXTRA_CONSENT_INTENT);
          smsBroadcastReceiverListener.onSuccess(messageIntent);
          break;
        case CommonStatusCodes.TIMEOUT:
          smsBroadcastReceiverListener.onFailure();
          break;
      }
    }
  }

  public interface SmsBroadcastReceiverListener {
    void onSuccess(Intent intent);

    void onFailure();
  }
}

When the broadcast receiver catch any message that contains OTP, Google paly services display is contents( BottomSheet ) for asking permission. If the user allows then full messing is available to your app. So let’s register broadcast receiver.

private void registerBroadcastReceiver() {
    smsBroadcastReceiver = new SmsBroadcastReceiver();
    smsBroadcastReceiver.smsBroadcastReceiverListener =
        new SmsBroadcastReceiver.SmsBroadcastReceiverListener() {
          @Override
          public void onSuccess(Intent intent) {
            startActivityForResult(intent, REQ_USER_CONSENT);
          }

          @Override
          public void onFailure() {

          }
        };
    IntentFilter intentFilter = new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION);
    registerReceiver(smsBroadcastReceiver, intentFilter);
  }

  @Override
  protected void onStart() {
    super.onStart();
    registerBroadcastReceiver();
  }

  @Override
  protected void onStop() {
    super.onStop();
    unregisterReceiver(smsBroadcastReceiver);
  }
6. Receive message in onActivityResult()

If the user consents, the entire SMS message is made available to your app. we will catch messaging in

 @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQ_USER_CONSENT) {
      if ((resultCode == RESULT_OK) && (data != null)) {
        //That gives all message to us.
        // We need to get the code from inside with regex
        String message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE);
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        textViewMessage.setText(
            String.format("%s - %s", getString(R.string.received_message), message));

        getOtpFromMessage(message);
      }
    }
  }
7. Extract OTP from messaging.

Suppose our messaging is “Your OTP is 123456. Please do not share OTP with others “. Now you have to extract OTP from methods using below method.

  private void getOtpFromMessage(String message) {
    // This will match any 6 digit number in the message
    Pattern pattern = Pattern.compile("(|^)\\d{6}");
    Matcher matcher = pattern.matcher(message);
    if (matcher.find()) {
      otpText.setText(matcher.group(0));
    }
  }
8. I’m modifying main activity layout for demonstration

For creating a fully functional sample app, I’m adding TextView for showing messaging and edit text for showing OTP.

<?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=".MainActivity"
    >

  <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/verify_otp"
      android:textAllCaps="false"
      android:textSize="18sp"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />
  <TextView
      android:id="@+id/textViewMessage"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginStart="16dp"
      android:layout_marginTop="24dp"
      android:layout_marginEnd="16dp"
      android:gravity="center"
      android:textSize="16sp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/button"
      tools:text="@string/received_message"
      />
  <ImageView
      android:id="@+id/imageView"
      android:layout_width="150dp"
      android:layout_height="150dp"
      android:layout_marginTop="32dp"
      app:layout_constraintBottom_toTopOf="@+id/editTextOTP"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:srcCompat="@drawable/ic_otp"
      />
  <EditText
      android:id="@+id/editTextOTP"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginStart="16dp"
      android:layout_marginEnd="16dp"
      android:layout_marginBottom="16dp"
      android:ems="10"
      android:gravity="center"
      android:hint="OTP"
      android:inputType="number"
      app:layout_constraintBottom_toTopOf="@+id/button"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      />

</androidx.constraintlayout.widget.ConstraintLayout>
9. We almost done, put all java code together in activity files.
package com.smsverification;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.auth.api.phone.SmsRetriever;
import com.google.android.gms.auth.api.phone.SmsRetrieverClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
  private static final int REQ_USER_CONSENT = 200;
  SmsBroadcastReceiver smsBroadcastReceiver;
  Button verifyOTP;
  TextView textViewMessage;
  EditText otpText;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // find view by ids
    verifyOTP = findViewById(R.id.button);
    textViewMessage = findViewById(R.id.textViewMessage);
    otpText = findViewById(R.id.editTextOTP);
    startSmsUserConsent();
  }

  private void startSmsUserConsent() {
    SmsRetrieverClient client = SmsRetriever.getClient(this);
    //We can add sender phone number or leave it blank
    // I'm adding null here
    client.startSmsUserConsent(null).addOnSuccessListener(new OnSuccessListener<Void>() {
      @Override
      public void onSuccess(Void aVoid) {
        Toast.makeText(getApplicationContext(), "On Success", Toast.LENGTH_LONG).show();
      }
    }).addOnFailureListener(new OnFailureListener() {
      @Override
      public void onFailure(@NonNull Exception e) {
        Toast.makeText(getApplicationContext(), "On OnFailure", Toast.LENGTH_LONG).show();
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQ_USER_CONSENT) {
      if ((resultCode == RESULT_OK) && (data != null)) {
        //That gives all message to us.
        // We need to get the code from inside with regex
        String message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE);
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        textViewMessage.setText(
            String.format("%s - %s", getString(R.string.received_message), message));

        getOtpFromMessage(message);
      }
    }
  }

  private void getOtpFromMessage(String message) {
    // This will match any 6 digit number in the message
    Pattern pattern = Pattern.compile("(|^)\\d{6}");
    Matcher matcher = pattern.matcher(message);
    if (matcher.find()) {
      otpText.setText(matcher.group(0));
    }
  }

  private void registerBroadcastReceiver() {
    smsBroadcastReceiver = new SmsBroadcastReceiver();
    smsBroadcastReceiver.smsBroadcastReceiverListener =
        new SmsBroadcastReceiver.SmsBroadcastReceiverListener() {
          @Override
          public void onSuccess(Intent intent) {
            startActivityForResult(intent, REQ_USER_CONSENT);
          }

          @Override
          public void onFailure() {

          }
        };
    IntentFilter intentFilter = new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION);
    registerReceiver(smsBroadcastReceiver, intentFilter);
  }

  @Override
  protected void onStart() {
    super.onStart();
    registerBroadcastReceiver();
  }

  @Override
  protected void onStop() {
    super.onStop();
    unregisterReceiver(smsBroadcastReceiver);
  }
}

Congrats, Let’s use the SMS content API is your application

Conclusion

In this post, we learned how to auto-read OTP android using SMS content API in our application. So let’s recap the step of implementation, basically, three major steps Start Listening messaging, show prompt and Read messaging.

 I hope it’s helpful for you, Help me by sharing this post with all your friends who learning android app development.

Get Solution Code

Keep Learning 🙂