Android Bridge for React Native | Communication in the Background and Killed State

By StartxLabs
Date 14-03-20
Android Bridge for React Native | Communication in the Background and Killed State
" Communication in the Background and Killed State"

 

About React Native

As we know with React Native we can create native apps for Android and iOS using React. It combines the best parts of native development with React, a best-in-class JavaScript library for building user interfaces.

Read More about React Native here

 

React Native Community

React Native Community is a wide community to help and contribute among peer developers in order to flourish React Native Support as well as its development.

All of the components provided by the React Native Community have been adopted by developers because of the ease of use and the functional requirement that React Native could not deliver with its library.

Read more about React Native Community here

 

Most of the Component developed by the community are Bridges between Platform Code (Code written in Java, Kotlin, Swift etc) and React Native Code(JS Code). 

 

So, What are bridges ????

Bridges also known as Native Modules, behaves as the Bridge (yeah, exactly like the bridge connecting two cities) between the Platform Code (Code written in Java, Kotlin, Swift etc) and React Native Code(JS Code). It helps in providing the communication between Platform Code and React Native code. 

 

Why Bridge is a thing in React Native?

Sometimes an app needs to access a platform API and React Native does not have a corresponding module yet. Perhaps we want to reuse some existing Java, Kotlin, Objective-C, Swift or C++ code without having to re implement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions. Then the concept of Native Module (Bridge) comes to rescue us.

Read More about Bridge here

 

Developing Native Module or Bridge

Developing the Native Module is pretty much easy, at least for Android and iOS Developer as compared to the React Native developer. Here the Native expertise helps them. 

 

Integrating the code in JS does not require expertise too, a React Native developer can easily integrate that, and also they do it on daily basis without being aware of it. There are various common functionality that is being provided by React Native itself are based on those bridges. For ex: Toast, DatePicker and many more and we use these. Don't we?

 

I'll not be discussing about the Developing the bridges in this post but you can learn more about Creating and Integrating the Bridges on the React Native official site for Android or iOS

 

By this time you guys must have started cursing me, as I didn't start with the Communication between Android Native Module with React Native in the Background and Killed State

Pic SourceGIPHY

 

 

Here we begin,

As we know we can communicate among different component in Andriod via Broadcast Sender and Reciever, whether it be in Foreground State, Background State or Killed State. However, this does not imply in React Native Application, I tried to fetch the Location in Background and Killed state via Broadcast Sender and Reciever but it didn't work that way. The Broadcast receiver does not wake the application.

 

For this specific scenario we have Headless Task in React Native that does help you with the same stuff.

 

Now what is this Headless Task?

As per React Native documentation, Headless Tasks are: 

Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music. Read More about it here

I did not go through this part of documentation before hand, else it would have saved me couple of hours I invested in Broadcast Reciever. So to make things easier for you guys I combined the stuff that can give you a good idea about implementing the same in your application, if facing a similar kind of situation.

 

Let's get started with code snippet attached

Pic Source: GIPHY

 

Android Platform Code wriiten in Kotlin to Implement HeadlessTaskService

 



import android.content.Intent
import com.facebook.react.HeadlessJsTaskService
import com.facebook.react.bridge.Arguments
import com.facebook.react.jstasks.HeadlessJsTaskConfig


class LocationHeadlessService : HeadlessJsTaskService() {

    val HEADLESS_TASK_NAME = "LocationTask"

    override fun getTaskConfig(intent: Intent?): HeadlessJsTaskConfig? {
        val extras = intent!!.extras
        return if (extras != null) {
            HeadlessJsTaskConfig(
                    HEADLESS_TASK_NAME,
                    Arguments.fromBundle(extras),
                    5000,  // timeout for the task
                    true // optional: defines whether or not  the task is allowed in foreground. Default is false
            )
        } else null
    }
}

 

How to call the HeadlessTaskService so that it communicates with the React Native Code:

 

val service = Intent(applicationContext, LocationHeadlessService::class.java)

val bundle = Bundle()

bundle.putDouble("latitude", location.latitude)
bundle.putDouble("longitude", location.longitude)

service.putExtras(bundle)
applicationContext.startService(service)

You can put the above code in your Android Service

Yes, it is as simple as that!!!

 

How to listen or recieve the data in React Native Application Code?

 

Just add the registerHeadlessTask line above your registerComponent as shown below


import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import headlessTask from './src/bridge/headlessTask';
import store from './src/store';

AppRegistry.registerHeadlessTask('LocationTask', () => headlessTask.bind(null, store));
AppRegistry.registerComponent(appName, () => App);

 

The headlessTask mentioned above will look like this

 

// This is headlessTask.js

export default async (store, data) => {
    // Your Handling Code here
    return Promise.resolve();
}

 

Ta Da you are done with it ! ! !

Pic Source: GIPHY
 

 

"We transform your idea into reality, reach out to us to discuss it.

or wanna join our cool team email us at [email protected] or see careers at startxlabs"

subscribe to startxlabs

startxlabs