Skip to content

Commit

Permalink
Android - Add a ReactFragment (facebook#12199)
Browse files Browse the repository at this point in the history
Summary:
React Native on Android has currently been focused and targeted at using an [Activity](https://developer.android.com/reference/android/app/Activity.html) for its main form of instantiation.

While this has probably worked for most companies and developers, you lose some of the modularity of a more cohesive application when working in a "brown-field" project that is currently native. This hurts more companies that are looking to adopt React Native and slowly implement it in a fully native application.

A lot of developers follow Android's guidelines of using Fragments in their projects, even if it is a debated subject in the Android community, and this addition will allow others to embrace React Native more freely. (I even assume it could help with managing navigation state in applications that contain a decent amount of Native code and would be appreciated in those projects. Such as sharing the Toolbar, TabBar, ViewPager, etc in Native Android)

Even with this addition, a developer will still need to host the fragment in an activity, but now that activity can contain native logic like a Drawer, Tabs, ViewPager, etc.

**Test plan (required)**
* We have been using this class at Hudl for over a couple of months and have found it valuable.
* If the community agrees on the addition, I can add documentation to the Android sections to include notes about the potential of this Fragment.
* If the community agrees on the addition, I can update one or more of the examples in the `/Examples` folder and make use of the Fragment, or even create a new example that uses a native layout manager like Drawer, Tabs, Viewpager, etc)

Make sure tests pass on both Travis and Circle CI.

_To Note:_
* There is also talk of using React Native inside Android Fragment's without any legit documentation, this could help remedy some of that with more documentation included in this PR https://facebook.github.io/react-native/releases/0.26/docs/embedded-app-android.html#sharing-a-reactinstance-across-multiple-activities-fragments-in-your-app
* Others have also requested something similar and have a half-baked solution as well http://stackoverflow.com/questions/35221447/react-native-inside-a-fragment

[ANDROID][FEATURE][ReactAndroid/src/main/java/com/facebook/react/ReactFragment.java] - Adds support for Android's Fragment system. This allows for a more hybrid application.
<!--
Help reviewers and the release process by writing your own release notes

**INTERNAL and MINOR tagged notes will not be included in the next version's final release notes.**

  CATEGORY
[----------]        TYPE
[ CLI      ]   [-------------]      LOCATION
[ DOCS     ]   [ BREAKING    ]   [-------------]
[ GENERAL  ]   [ BUGFIX      ]   [-{Component}-]
[ INTERNAL ]   [ ENHANCEMENT ]   [ {File}      ]
[ IOS      ]   [ FEATURE     ]   [ {Directory} ]   |-----------|
[ ANDROID  ]   [ MINOR       ]   [ {Framework} ] - | {Message} |
[----------]   [-------------]   [-------------]   |-----------|

[CATEGORY] [TYPE] [LOCATION] - MESSAGE

 EXAMPLES:

 [IOS] [BREAKING] [FlatList] - Change a thing that breaks other things
 [ANDROID] [BUGFIX] [TextInput] - Did a thing to TextInput
 [CLI] [FEATURE] [local-cli/info/info.js] - CLI easier to do things with
 [DOCS] [BUGFIX] [GettingStarted.md] - Accidentally a thing/word
 [GENERAL] [ENHANCEMENT] [Yoga] - Added new yoga thing/position
 [INTERNAL] [FEATURE] [./scripts] - Added thing to script that nobody will see
-->
Pull Request resolved: facebook#12199

Differential Revision: D14590665

Pulled By: mdvacca

fbshipit-source-id: b50b708cde458f9634e0c14b3952fa32f9d82048
  • Loading branch information
jpshelley authored and facebook-github-bot committed Apr 4, 2019
1 parent e62cfc0 commit 691f2f9
Show file tree
Hide file tree
Showing 3 changed files with 373 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@

import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.Callback;
import com.facebook.react.devsupport.DoubleTapReloadRecognizer;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.PermissionListener;

import com.facebook.react.uimanager.RootView;
import javax.annotation.Nullable;

/**
Expand All @@ -31,10 +30,10 @@ public class ReactActivityDelegate {
private final @Nullable Activity mActivity;
private final @Nullable String mMainComponentName;

private @Nullable ReactRootView mReactRootView;
private @Nullable DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;
private @Nullable PermissionListener mPermissionListener;
private @Nullable Callback mPermissionsCallback;
private ReactDelegate mReactDelegate;


@Deprecated
public ReactActivityDelegate(Activity activity, @Nullable String mainComponentName) {
Expand All @@ -52,7 +51,7 @@ public ReactActivityDelegate(ReactActivity activity, @Nullable String mainCompon
}

protected ReactRootView createRootView() {
return new ReactRootView(getContext());
return mReactDelegate.createRootView();
}

/**
Expand All @@ -67,7 +66,7 @@ protected ReactNativeHost getReactNativeHost() {
}

public ReactInstanceManager getReactInstanceManager() {
return getReactNativeHost().getReactInstanceManager();
return mReactDelegate.getReactInstanceManager();
}

public String getMainComponentName() {
Expand All @@ -76,36 +75,24 @@ public String getMainComponentName() {

protected void onCreate(Bundle savedInstanceState) {
String mainComponentName = getMainComponentName();
if (mainComponentName != null) {
loadApp(mainComponentName);
mReactDelegate = new ReactDelegate(getPlainActivity(), getReactNativeHost(), mainComponentName, getLaunchOptions());
if (mMainComponentName != null) {
mReactDelegate.loadApp();
getPlainActivity().setContentView(mReactDelegate.getReactRootView());
}
mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
}

protected void loadApp(String appKey) {
if (mReactRootView != null) {
throw new IllegalStateException("Cannot loadApp while app is already running.");
}
mReactRootView = createRootView();
mReactRootView.startReactApplication(
getReactNativeHost().getReactInstanceManager(),
appKey,
getLaunchOptions());
getPlainActivity().setContentView(mReactRootView);
mReactDelegate.loadApp(appKey);
getPlainActivity().setContentView(mReactDelegate.getReactRootView());
}

protected void onPause() {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onHostPause(getPlainActivity());
}
mReactDelegate.onHostPause();
}

protected void onResume() {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onHostResume(
getPlainActivity(),
(DefaultHardwareBackBtnHandler) getPlainActivity());
}
mReactDelegate.onHostResume();

if (mPermissionsCallback != null) {
mPermissionsCallback.invoke();
Expand All @@ -114,20 +101,11 @@ protected void onResume() {
}

protected void onDestroy() {
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
}
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onHostDestroy(getPlainActivity());
}
mReactDelegate.onHostDestroy();
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager()
.onActivityResult(getPlainActivity(), requestCode, resultCode, data);
}
mReactDelegate.onActivityResult(requestCode, resultCode, data, true);
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
Expand All @@ -141,19 +119,7 @@ && getReactNativeHost().getUseDeveloperSupport()
}

public boolean onKeyUp(int keyCode, KeyEvent event) {
if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
getReactNativeHost().getReactInstanceManager().showDevOptionsDialog();
return true;
}
boolean didDoubleTapR = Assertions.assertNotNull(mDoubleTapReloadRecognizer)
.didDoubleTapR(keyCode, getPlainActivity().getCurrentFocus());
if (didDoubleTapR) {
getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS();
return true;
}
}
return false;
return mReactDelegate.shouldShowDevMenuOrReload(keyCode, event);
}

public boolean onKeyLongPress(int keyCode, KeyEvent event) {
Expand All @@ -167,11 +133,7 @@ && getReactNativeHost().getUseDeveloperSupport()
}

public boolean onBackPressed() {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onBackPressed();
return true;
}
return false;
return mReactDelegate.onBackPressed();
}

public boolean onNewIntent(Intent intent) {
Expand Down
147 changes: 147 additions & 0 deletions ReactAndroid/src/main/java/com/facebook/react/ReactDelegate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

package com.facebook.react;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import com.facebook.infer.annotation.Assertions;
import com.facebook.react.devsupport.DoubleTapReloadRecognizer;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;

import javax.annotation.Nullable;

/**
* A delegate for handling React Application support. This delegate is unaware whether it is used in
* an {@link Activity} or a {@link android.app.Fragment}.
*/
public class ReactDelegate {

private final Activity mActivity;
private ReactRootView mReactRootView;

@Nullable
private final String mMainComponentName;

@Nullable
private Bundle mLaunchOptions;

@Nullable
private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;

private ReactNativeHost mReactNativeHost;


public ReactDelegate(Activity activity, ReactNativeHost reactNativeHost, @Nullable String appKey, @Nullable Bundle launchOptions) {
mActivity = activity;
mMainComponentName = appKey;
mLaunchOptions = launchOptions;
mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
mReactNativeHost = reactNativeHost;
}

public void onHostResume() {
if (getReactNativeHost().hasInstance()) {
if (mActivity instanceof DefaultHardwareBackBtnHandler) {
getReactNativeHost().getReactInstanceManager().onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity);
} else {
throw new ClassCastException("Host Activity does not implement DefaultHardwareBackBtnHandler");
}
}
}

public void onHostPause() {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onHostPause(mActivity);
}
}

public void onHostDestroy() {
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
}
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onHostDestroy(mActivity);
}
}

public boolean onBackPressed() {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onBackPressed();
return true;
}
return false;
}

public void onActivityResult(int requestCode, int resultCode, Intent data, boolean shouldForwardToReactInstance) {
if (getReactNativeHost().hasInstance() && shouldForwardToReactInstance) {
getReactNativeHost().getReactInstanceManager().onActivityResult(mActivity, requestCode, resultCode, data);
}
}

public void loadApp() {
loadApp(mMainComponentName);
}

public void loadApp(String appKey) {
if (mReactRootView != null) {
throw new IllegalStateException("Cannot loadApp while app is already running.");
}
mReactRootView = createRootView();
mReactRootView.startReactApplication(
getReactNativeHost().getReactInstanceManager(),
appKey,
mLaunchOptions);

}

public ReactRootView getReactRootView() {
return mReactRootView;
}


protected ReactRootView createRootView() {
return new ReactRootView(mActivity);
}

/**
* Handles delegating the {@link Activity#onKeyUp(int, KeyEvent)} method to determine whether
* the application should show the developer menu or should reload the React Application.
*
* @return true if we consume the event and either shoed the develop menu or reloaded the application.
*/
public boolean shouldShowDevMenuOrReload(int keyCode, KeyEvent event) {
if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
getReactNativeHost().getReactInstanceManager().showDevOptionsDialog();
return true;
}
boolean didDoubleTapR = Assertions.assertNotNull(mDoubleTapReloadRecognizer).didDoubleTapR(keyCode, mActivity.getCurrentFocus());
if (didDoubleTapR) {
getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS();
return true;
}
}
return false;
}

/**
* Get the {@link ReactNativeHost} used by this app.
*/
private ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}

public ReactInstanceManager getReactInstanceManager() {
return getReactNativeHost().getReactInstanceManager();
}

}
Loading

0 comments on commit 691f2f9

Please sign in to comment.