Integration with Existing Apps #

本文档详细介绍了如何将React Native组件集成到现有的Android应用中。包括设置目录结构、安装依赖、配置Gradle文件、添加React Native视图等步骤,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

React Native is great when you are starting a new mobile app from scratch. However, it also works well for adding a single view or user flow to existing native applications. With a few steps, you can add new React Native based features, screens, views, etc.

The specific steps are different depending on what platform you're targeting.

  • iOS (Objective-C)
  • iOS (Swift)
  • Android (Java)

Key Concepts

The keys to integrating React Native components into your Android application are to:

  1. Set up React Native dependencies and directory structure.
  2. Develop your React Native components in JavaScript.
  3. Add a ReactRootView to your Android app. This view will serve as the container for your React Native component.
  4. Start the React Native server and run your native application.
  5. Verify that the React Native aspect of your application works as expected.

Prerequisites

Follow the instructions for building apps with native code from the Getting Started guide to configure your development environment for building React Native apps for Android.

1. Set up directory structure

To ensure a smooth experience, create a new folder for your integrated React Native project, then copy your existing Android project to a /android subfolder.

2. Install JavaScript dependencies

Go to the root directory for your project and create a new package.json file with the following contents:

{ "name" : "MyReactNativeApp" , "version" : "0.0.1" , "private" : true , "scripts" : { "start" : "node node_modules/react-native/local-cli/cli.js start" } }

Next, you will install the react and react-native packages. Open a terminal or command prompt, then navigate to the root directory for your project and type the following commands:

$ npm install --save react@ 16.0 . 0 -beta .5 react -native

Make sure you use the same React version as specified in the React Native package.json file. This will only be necessary as long as React Native depends on a pre-release version of React.

This will create a new /node_modules folder in your project's root directory. This folder stores all the JavaScript dependencies required to build your project.

Adding React Native to your app

Configuring maven

Add the React Native dependency to your app's build.gradle file:

dependencies { ... compile "com.facebook.react:react-native:+" // From node_modules. }

If you want to ensure that you are always using a specific React Native version in your native build, replace + with an actual React Native version you've downloaded from npm.

Add an entry for the local React Native maven directory to build.gradle. Be sure to add it to the "allprojects" block:

allprojects { repositories { ... maven { // All of React Native (JS, Android binaries) is installed from npm url "$rootDir/node_modules/react-native/android" } } ... }

Make sure that the path is correct! You shouldn’t run into any “Failed to resolve: com.facebook.react:react-native:0.x.x" errors after running Gradle sync in Android Studio.

Configuring permissions

Next, make sure you have the Internet permission in your AndroidManifest.xml:

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

If you need to access to the DevSettingsActivity add to your AndroidManifest.xml:

<activity android :name = "com.facebook.react.devsupport.DevSettingsActivity" / >

This is only really used in dev mode when reloading JavaScript from the development server, so you can strip this in release builds if you need to.

Code integration

Now we will actually modify the native Android application to integrate React Native.

The React Native component

The first bit of code we will write is the actual React Native code for the new "High Score" screen that will be integrated into our application.

1. Create a index.js file

First, create an empty index.js file in the root of your React Native project.

index.js is the starting point for React Native applications, and it is always required. It can be a small file that requires other file that are part of your React Native component or application, or it can contain all the code that is needed for it. In our case, we will just put everything in index.js.

2. Add your React Native code

In your index.js, create your component. In our sample here, we will add simple <Text> component within a styled <View>:

'use strict' ; import React from 'react' ; import { AppRegistry , StyleSheet , Text , View } from 'react-native' ; class HelloWorld extends React.Component { render ( ) { return ( <View style = {styles .container } > <Text style = {styles .hello } >Hello , World < /Text > < /View > ) } } var styles = StyleSheet . create ( { container : { flex : 1 , justifyContent : 'center' , } , hello : { fontSize : 20 , textAlign : 'center' , margin : 10 , } , } ) ;AppRegistry . registerComponent ( 'MyReactNativeApp' , ( ) => HelloWorld ) ;
3. Configure permissions for development error overlay

If your app is targeting the Android API level 23 or greater, make sure you have the overlay permission enabled for the development build. You can check it with Settings.canDrawOverlays(this);. This is required in dev builds because react native development errors must be displayed above all the other windows. Due to the new permissions system introduced in the API level 23, the user needs to approve it. This can be achieved by adding the following code to the Activity file in the onCreate() method. OVERLAY_PERMISSION_REQ_CODE is a field of the class which would be responsible for passing the result back to the Activity.

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 ) ; } }

Finally, the onActivityResult() method (as shown in the code below) has to be overridden to handle the permission Accepted or Denied cases for consistent UX.

@Override protected void onActivityResult( int requestCode , int resultCode , Intent data ) { if (requestCode == OVERLAY_PERMISSION_REQ_CODE ) { if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .M ) { if ( !Settings . canDrawOverlays( this ) ) { // SYSTEM_ALERT_WINDOW permission not granted... } } } }
The Magic: ReactRootView

You need to add some native code in order to start the React Native runtime and get it to render something. To do this, we're going to create an Activity that creates a ReactRootView, starts a React application inside it and sets it as the main content view.

If you are targetting Android version <5, use the AppCompatActivity class from the com.android.support:appcompat package instead of Activity.

public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler { private ReactRootView mReactRootView ; private ReactInstanceManager mReactInstanceManager ; @Override protected void onCreate(Bundle savedInstanceState ) { super . onCreate(savedInstanceState ) ; mReactRootView = new ReactRootView ( this ) ; mReactInstanceManager = ReactInstanceManager . builder( ) . setApplication( getApplication( ) ) . setBundleAssetName( "index.android.bundle" ) . setJSMainModulePath( "index" ) . addPackage( new MainReactPackage ( ) ) . setUseDeveloperSupport(BuildConfig .DEBUG ) . setInitialLifecycleState(LifecycleState .RESUMED ) . build( ) ; mReactRootView . startReactApplication(mReactInstanceManager , "MyReactNativeApp" , null ) ; setContentView(mReactRootView ) ; } @Override public void invokeDefaultOnBackPressed( ) { super . onBackPressed( ) ; } }

If you are using a starter kit for React Native, replace the "HelloWorld" string with the one in your index.js file (it’s the first argument to the AppRegistry.registerComponent() method).

If you are using Android Studio, use Alt + Enter to add all missing imports in your MyReactActivity class. Be careful to use your package’s BuildConfig and not the one from the ...facebook... package.

We need set the theme of MyReactActivity to Theme.AppCompat.Light.NoActionBar because some components rely on this theme.

<activity android:name=".MyReactActivity" android:label="@string/app_name" android:theme="@style/Theme.AppCompat.Light.NoActionBar"></activity>

A ReactInstanceManager can be shared amongst multiple activities and/or fragments. You will want to make your own ReactFragment or ReactActivity and have a singleton holder that holds a ReactInstanceManager. When you need the ReactInstanceManager (e.g., to hook up the ReactInstanceManager to the lifecycle of those Activities or Fragments) use the one provided by the singleton.

Next, we need to pass some activity lifecycle callbacks down to the ReactInstanceManager:

@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( ) ; } }

We also need to pass back button events to React Native:

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

This allows JavaScript to control what happens when the user presses the hardware back button (e.g. to implement navigation). When JavaScript doesn't handle a back press, your invokeDefaultOnBackPressed method will be called. By default this simply finishes your Activity.

Finally, we need to hook up the dev menu. By default, this is activated by (rage) shaking the device, but this is not very useful in emulators. So we make it show when you press the hardware menu button (use Ctrl + M if you're using Android Studio emulator):

@Override public boolean onKeyUp( int keyCode , KeyEvent event ) { if (keyCode == KeyEvent .KEYCODE_MENU && mReactInstanceManager != null ) { mReactInstanceManager . showDevOptionsDialog( ) ; return true ; } return super . onKeyUp(keyCode , event ) ; }

Now your activity is ready to run some JavaScript code.

Test your integration

You have now done all the basic steps to integrate React Native with your current application. Now we will start the React Native packager to build the index.bundle package and the server running on localhost to serve it.

1. Run the packager

To run your app, you need to first start the development server. To do this, simply run the following command in the root directory of your React Native project:

$ npm start
2. Run the app

Now build and run your Android app as normal.

Once you reach your React-powered activity inside the app, it should load the JavaScript code from the development server and display:

Screenshot

Creating a release build in Android Studio

You can use Android Studio to create your release builds too! It’s as easy as creating release builds of your previously-existing native Android app. There’s just one additional step, which you’ll have to do before every release build. You need to execute the following to create a React Native bundle, which will be included with your native Android app:

$ react -native bundle --platform android --dev false --entry -file index .js --bundle -output android /com /your -company -name /app - package -name /src /main /assets /index .android .bundle --assets -dest android /com /your -company -name /app - package -name /src /main /res/

Don’t forget to replace the paths with correct ones and create the assets folder if it doesn’t exist.

Now just create a release build of your native app from within Android Studio as usual and you should be good to go!

Now what?

At this point you can continue developing your app as usual. Refer to our debugging and deployment docs to learn more about working with React Native.

Improve this page by sending a pull request!





内容概要:本文档详细介绍了基于Google Earth Engine (GEE) 构建的阿比让绿地分析仪表盘的设计与实现。首先,定义了研究区域的几何图形并将其可视化。接着,通过云掩膜函数和裁剪操作预处理Sentinel-2遥感影像,筛选出高质量的数据用于后续分析。然后,计算中值图像并提取NDVI(归一化差异植被指数),进而识别绿地及其面积。此外,还实现了多个高级分析功能,如多年变化趋势分析、人口-绿地交叉分析、城市热岛效应分析、生物多样性评估、交通可达性分析、城市扩张分析以及自动生成优化建议等。最后,提供了数据导出、移动端适配和报告生成功能,确保系统的实用性和便捷性。 适合人群:具备一定地理信息系统(GIS)和遥感基础知识的专业人士,如城市规划师、环境科学家、生态学家等。 使用场景及目标:①评估城市绿地分布及其变化趋势;②分析绿地与人口的关系,为城市规划提供依据;③研究城市热岛效应及生物多样性,支持环境保护决策;④评估交通可达性,优化城市交通网络;⑤监测城市扩张情况,辅助土地利用管理。 其他说明:该系统不仅提供了丰富的可视化工具,还集成了多种空间分析方法,能够帮助用户深入理解城市绿地的空间特征及其对环境和社会的影响。同时,系统支持移动端适配,方便随时随地进行分析。用户可以根据实际需求选择不同的分析模块,生成定制化的报告,为城市管理提供科学依据。
Group az webapp : Manage web apps. Subgroups: auth : Manage webapp authentication and authorization. To use v2 auth commands, run "az extension add --name authV2" to add the authV2 CLI extension. config : Configure a web app. connection : Commands to manage webapp connections. cors : Manage Cross-Origin Resource Sharing (CORS). deleted [Preview] : Manage deleted web apps. deployment : Manage web app deployments. hybrid-connection : Methods that list, add and remove hybrid-connections from webapps. identity : Manage web app&#39;s managed identity. log : Manage web app logs. sitecontainers : Manage linux web apps sitecontainers. traffic-routing : Manage traffic routing for web apps. vnet-integration : Methods that list, add, and remove virtual network integrations from a webapp. webjob : Allows management operations for webjobs on a web app. Commands: browse : Open a web app in a browser. This is not supported in Azure Cloud Shell. create : Create a web app. create-remote-connection : Creates a remote connection using a tcp tunnel to your web app. delete : Delete a web app. deploy : Deploys a provided artifact to Azure Web Apps. list : List web apps. list-instances : List all scaled out instances of a web app or web app slot. list-runtimes : List available built-in stacks which can be used for web apps. restart : Restart a web app. show : Get the details of a web app. ssh [Preview] : SSH command establishes a ssh session to the web container and developer would get a shell terminal remotely. start : Start a web app. stop : Stop a web app. up : Create a webapp and deploy code from a local workspace to the app. The command is required to run from the folder where the code is present. Current support includes Node, Python, .NET Core and ASP.NET. Node, Python apps are created as Linux apps. .Net Core, ASP.NET, and static HTML apps are created as Windows apps. Append the html flag to deploy as a static HTML app. Each time the command is successfully run, default argument values for resource group, sku, location, plan, and name are saved for the current directory. These defaults are then used for any arguments not provided on subsequent runs of the command in the same directory. Use &#39;az configure&#39; to manage defaults. Run this command with the --debug parameter to see the API calls and parameters values being used. update : Update an existing web app. To search AI knowledge base for examples, use: az find "az webapp" You have 2 update(s) available. They will be updated with the next build of Cloud Shell.
05-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值