A Complete Guide to Integrating Native Android Apps with React Native

Posted By : Aakash

Jul 21, 2023

As a tech enthusiast, you may already know that React Native is a powerful framework for building mobile apps from scratch. However, what's even more impressive is how seamlessly it integrates with existing native applications, allowing you to effortlessly incorporate new features, screens, and views. Developers can leverage blockchain development services, developers can seamlessly integrate a native Android app with React Native, ensuring enhanced security and efficiency in the mobile application. In this article, we'll explore how you can supercharge your existing native apps with React Native, expanding their capabilities and user experience.

 

Integrating Native Android Apps with React Native

 

Important Guidelines: Refer to the React Native CLI Quickstart in the environment configuration guide to set up your development environment for creating React Native applications for Android.

 

Set Up React Native Dependencies and Directory Structure

 

First things first, ensure you have all the necessary React Native dependencies set up in your project. This includes installing the required packages and configuring your development environment. Additionally, organizing your project's directory structure efficiently will make it easier to manage your code as you progress.

 

You May Also Like | Android App Development | A Beginner’s Guide

 

Let’s quickly copy our android project into “/android“ folder in a blank folder, then create a new file with the name “package.json”

 

{
  "name": “AwesomeApp", //your project name here
  "version": “0.0.1”, //version number
  "private": true,
  "scripts": {
    "start": “npx react-native start" //add scripts here
  }
}

 

Now, we need to install React and React Native into our project. Open a terminal in the directory where you have the recently created "package.json" file and execute the following commands:

 

Step 1: Install React Native

 

npm install react-native

 

After executing this command, React Native will be installed in your project.

 

Step 2: Install React (Address the Warning)

 

You may encounter a warning related to React. To resolve this, follow these steps:

 

a) Copy the version number of React that is specified in the warning.

 

b) Run the following command to install the required version of React:

 

npm install react@version_number
 

 

By doing so, we'll ensure that the correct version of React is installed in conjunction with React Native.

 

To ensure that this folder doesn't clutter your version control system, it's crucial to add "node_modules/" to your .gitignore file. By doing so, you prevent unnecessary files from being tracked, resulting in a cleaner repository with only the essential source code and configuration files. This practice not only makes version control more efficient but also ensures a smoother collaboration with your team when working on the project.

 

Suggested Read | A Beginner's Guide to Web App Development

 

Configure Gradle

 

Let's make a modification to your existing settings.gradle file by adding the following line:

 

includeBuild('../node_modules/@react-native/gradle-plugin')



This addition will enable the Gradle Plugin to handle the necessary configurations and ensure a smooth integration of React Native into your project.

 

Now open your build.gradle from "/android" folder and add the following code into it:

 

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:7.3.1")
//————————add the following line from ————————
      classpath("com.facebook.react:react-native-gradle-plugin")
//————————upto here————————
    }
}

 

Now updated your app level gradle file ( it's indside /android/app folder)

 

apply plugin: "com.android.application"

 //————————add the following line from ————————
apply plugin: "com.facebook.react"
//————————upto here————————

repositories {
    mavenCentral()
}
dependencies {
   //————————add the following line from ————————
   implementation "com.facebook.react:react-android"
   implementation "com.facebook.react:hermes-android"
//————————upto here————————
}

 

Check It Out | Web3 App Development | Building a Decentralized Future

 

Adding Permissions

 

Make sure that you have added all of the required permissions needed for your app, I'm adding internet permission to the AndroidManifest file.

 

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

 

Also, add the usesCleartextTraffic so our app can connect to the metro bundler.

 

<application
  android:usesCleartextTraffic="true" 
  tools:targetApi="28" >
  <!-- rest manifest file code here -->
</application>

 

Also, Discover | NFT Ticketing Marketplace | Unlocking the Future of Ticketing

 

Build Some Components

 

With your project set up, it's time to put your JavaScript skills to work. Develop your desired React Native components using the power of React's declarative approach. This allows you to create dynamic and reusable UI elements, which will seamlessly integrate with your Android app.

 

Let's dive into writing the initial React Native code for the "High Score" screen, which will seamlessly integrate into our application.

 

Step 1: Create index.js

 

File To begin, navigate to the root of your React Native project and create an empty file named "index.js."

 

This index.js file serves as the entry point for React Native applications and is essential for your project. It can act as a small file that imports other components and files crucial for your React Native app or contain all the code necessary for the application. For simplicity, we'll include everything in this index.js file.

 

Step 2: Writing React Native Code Inside the index.js File

 

You can now create your React Native component. For this example, we'll implement a basic "High Score" screen with a styled <View> containing a <Text> component:

 

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

const HighScoreScreen = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.header}>High Score Screen</Text>
      {/* Add more components and UI elements here */}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
  },
  header: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  // Add more styles for other components here
});

AppRegistry.registerComponent(
'MyReactNativeApp',
() => HighScoreScreen,
);

 

 

Configuring permissions for the development error overlay is essential to ensure smooth debugging and error handling in your React Native app. By following these steps, you can enable the necessary permissions:

 

Check Android API Level: Ensure that your app targets Android API level 23 or higher, as the new permissions system was introduced in Android M (API level 23).

 

Enable android.permission.SYSTEM_ALERT_WINDOW: Make sure the permission android.permission.SYSTEM_ALERT_WINDOW is enabled for the development build. This permission allows React Native development errors to be displayed above all other windows during development.

 

private final int OVERLAY_PERMISSION_REQ_CODE = 1; 
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (!Settings.canDrawOverlays(this)) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                                   Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
    }
}

 

In conclusion, it is crucial to override the onActivityResult() method (as illustrated in the code snippet below) to handle both cases when the permission is accepted or denied, ensuring a consistent user experience. Additionally, when integrating Native Modules that utilize startActivityForResult, it's necessary to pass the result to the onActivityResult() method of our ReactInstanceManager instance to facilitate seamless communication between React Native and native modules.

 

private final int OVERLAY_PERMISSION_REQ_CODE = 1; 
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (!Settings.canDrawOverlays(this)) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                                   Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
    }
}


 

 

Explore More | ERC-1155 | An Introduction to Multi-Token Standard Development

 

Integrate a ReactRootView into Your Android Application

 

To make React Native and your Android app play well together, you need a special container – the ReactRootView. Think of it as a bridge between your React Native components and the Android native environment. This way, your components have a designated place to render and coexist harmoniously with the rest of your app.

 

Now create a new Java file parallel to your main activity file and paste the following code into it.

 

public class MyActivity extends Activity implements DefaultHardwareBackBtnHandler {
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SoLoader.init(this, false);

        mReactRootView = new ReactRootView(this);
        List<ReactPackage> packages = new PackageList(getApplication()).getPackages();

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setCurrentActivity(this)
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackages(packages)
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        // The string here (e.g. "MyReactNativeApp") has to match
        // the string in AppRegistry.registerComponent() in index.js
        mReactRootView.startReactApplication(mReactInstanceManager, “YOUR APP NAME HERE”, null);


        setContentView(mReactRootView);
    }

@Override
protected void onPause() {
    super.onPause();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onHostPause(this);
    }
}

@Override
protected void onResume() {
    super.onResume();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onHostResume(this, this);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onHostDestroy(this);
    }
    if (mReactRootView != null) {
        mReactRootView.unmountReactApplication();
    }
}

    @Override
    public void invokeDefaultOnBackPressed() {
        if (mReactInstanceManager != null) {
        mReactInstanceManager.onBackPressed();
    } else {
        super.onBackPressed();
        }
}

 

So in the above file, we have passed some callbacks to control the lifecycle events of the react app and a back button handler.

 

Now we just need to run our app, before that we need to run our javascript bundle we can use the following command:

 

npm start

 

Now we can run our Android app from Android Studio as we do normally. 

 

Looking for developers to integrate native Android apps with React Native? Connect with our experts today! 

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

September 7, 2024 at 06:08 pm

Your comment is awaiting moderation.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.

Chat with Us
Telegram Button
Youtube Button
Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text