将React Native集成到现有Android应用程序中,可以通过以下步骤完成:
npm install -g react-native-cli
react-native init MyReactModule
这将在你的项目目录下创建一个名为MyReactModule的新文件夹,其中包含React Native的初始项目结构。
include ':app', ':MyReactModule'
project(':MyReactModule').projectDir = new File(rootProject.projectDir, '../MyReactModule')
implementation project(':MyReactModule')
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
public class MainActivity extends AppCompatActivity 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, "MyReactModule", null);
setContentView(mReactRootView);
}
// ...其他代码
}
<uses-permission android:name="android.permission.INTERNET" />
<activity
android:name="com.facebook.react.devsupport.DevSettingsActivity"
android:screenOrientation="portrait"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize"
android:exported="true" />
<meta-data
android:name="com.facebook.react.ReactPackage"
android:value="com.facebook.react.shell.MainReactPackage" />
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
```java
@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);
}
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
```
```
react-native start
```
```
react-native run-android
```
完成以上步骤后,React Native将成功集成到你的现有Android应用程序中。你可以在React Native模块中编写和运行React Native代码,并在你的应用程序中使用React Native组件和功能。
领取专属 10元无门槛券
手把手带您无忧上云