{"id":517,"date":"2023-02-25T15:35:01","date_gmt":"2023-02-25T07:35:01","guid":{"rendered":"https:\/\/www.appblog.cn\/?p=517"},"modified":"2023-04-29T20:44:43","modified_gmt":"2023-04-29T12:44:43","slug":"react-native-learning-rn-and-native-communication","status":"publish","type":"post","link":"https:\/\/www.appblog.cn\/index.php\/2023\/02\/25\/react-native-learning-rn-and-native-communication\/","title":{"rendered":"React Native\u5b66\u4e60\u4e4bRN\u4e0e\u539f\u751f\u901a\u4fe1"},"content":{"rendered":"<p>React Native\u4e0e\u539f\u751f\u901a\u4fe1\uff0c\u672c\u6587\u9002\u914dAndroid\u539f\u751f\u4e0eRN\u7684\u6df7\u5408\u5f00\u53d1<\/p>\n<h2>\u5b9e\u4f8b\u4e00\uff1a\u9875\u9762\u8df3\u8f6c<\/h2>\n<p>RN\u89e6\u53d1Android\u539f\u751f\u7684\u65b9\u6cd5\uff1a\uff08\u542f\u52a8\u4e00\u4e2a\u65b0\u7684\u539f\u751f\u754c\u9762Activity\uff09\u754c\u9762\u5207\u6362<\/p>\n<p><!-- more --><\/p>\n<p>\u5f00\u542f\u610f\u56fe\u4e00\u5b9a\u8981\u6dfb\u52a0\u8bed\u53e5\uff1a<\/p>\n<pre><code class=\"language-java\">intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<\/code><\/pre>\n<p>MyNativeModule.java<\/p>\n<pre><code class=\"language-java\">public class MyNativeModule extends ReactContextBaseJavaModule {\n\n    private ReactApplicationContext context;\n\n    public MyNativeModule(ReactApplicationContext reactContext) {\n        super(reactContext);\n        context = reactContext;\n    }\n\n    @Override\n    public String getName() {\n        \/\/\u4e00\u5b9a\u8981\u8fd4\u56de\u4e00\u4e2a\u540d\u5b57\uff0c\u5728RN\u4ee3\u7801\u91cc\u9762\u9700\u8981\u4f7f\u7528\u8fd9\u4e2a\u540d\u5b57\u6765\u8c03\u7528\u8be5\u7c7b\u7684\u65b9\u6cd5\n        return &quot;MyNativeModule&quot;;\n    }\n\n    \/\/\u51fd\u6570\u4e0d\u80fd\u6709\u8fd4\u56de\u503c\uff0c\u56e0\u4e3a\u88ab\u8c03\u7528\u7684\u539f\u751f\u4ee3\u7801\u662f\u5f02\u6b65\u7684\uff0c\u539f\u751f\u4ee3\u7801\u6267\u884c\u7ed3\u675f\u4e4b\u540e\u53ea\u80fd\u901a\u8fc7\u56de\u8c03\u51fd\u6570\u6216\u8005\u53d1\u9001\u6d88\u606f\u7ed9RN\n    \/\/\u5fc5\u987b\u58f0\u660eReactMethod\u6ce8\u89e3\n    @ReactMethod\n    public void rnCallNative(String msg) {\n        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();\n\n        Intent intent = new Intent(context, MyActivity.class);\n        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); \/\/\u5fc5\u987b\u6dfb\u52a0\u8fd9\u6761\u8bed\u53e5\uff0c\u5426\u5219\u62a5\u9519\n        context.startActivity(intent);\n    }\n}<\/code><\/pre>\n<p>MyActivity.java<\/p>\n<pre><code class=\"language-java\">public class MyActivity extends AppCompatActivity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_my);\n    }\n\n    public void onBack(View v) {\n        finish();\n    }\n}<\/code><\/pre>\n<p>activity_my.xml<\/p>\n<pre><code class=\"language-xml\">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;\n&lt;RelativeLayout\n    android:layout_width=&quot;match_parent&quot;\n    android:layout_height=&quot;match_parent&quot;\n    xmlns:android=&quot;http:\/\/schemas.android.com\/apk\/res\/android&quot;\n    &gt;\n    &lt;Button\n        android:text=&quot;\u539f\u751f\u6309\u94ae - \u70b9\u51fb\u9000\u51fa&quot;\n        android:onClick=&quot;onBack&quot;\n        android:layout_centerInParent=&quot;true&quot;\n        android:layout_width=&quot;wrap_content&quot;\n        android:layout_height=&quot;wrap_content&quot;\n        android:background=&quot;#3BC1FF&quot;\n        android:paddingLeft=&quot;10dp&quot;\n        android:paddingRight=&quot;10dp&quot;\n        android:textColor=&quot;#FFFFFF&quot;\n        \/&gt;\n&lt;\/RelativeLayout&gt;<\/code><\/pre>\n<p>index.android.js<\/p>\n<pre><code class=\"language-javascript\">\/**\n * Sample React Native App\n * https:\/\/github.com\/facebook\/react-native\n * @flow\n *\/\n\nimport React, { Component } from &#039;react&#039;;\nimport {\n    AppRegistry,\n    StyleSheet,\n    Text,\n    View,\n    NativeModules\n} from &#039;react-native&#039;;\n\nclass RNAPP extends Component {\n    render() {\n        return (\n            &lt;View style={styles.container}&gt;\n                &lt;Text style={styles.welcome}&gt;\n                    Welcome to React Native!\n                &lt;\/Text&gt;\n                &lt;Text style={styles.welcome}&gt;\n                    React Native\u6df7\u5408\u539f\u751f\u5f00\u53d1\n                &lt;\/Text&gt;\n                &lt;Text style={styles.instructions}&gt;\n                    Powered by rnapp.cc\n                &lt;\/Text&gt;\n                &lt;Text onPress={this.callNative.bind(this)} style={styles.btn}&gt;\u9875\u9762\u8df3\u8f6c&lt;\/Text&gt;\n            &lt;\/View&gt;\n        );\n    }\n\n    callNative() {\n        NativeModules.MyNativeModule.rnCallNative(&#039;React Native \u8c03\u7528\u539f\u751f\u6a21\u5757\u7684\u65b9\u6cd5\\nPowered by RNAPP.CC&#039;);\n    }\n}\n\nconst styles = StyleSheet.create({\n    container: {\n        flex: 1,\n        justifyContent: &#039;center&#039;,\n        alignItems: &#039;center&#039;,\n        backgroundColor: &#039;#F5FCFF&#039;,\n    },\n    welcome: {\n        fontSize: 20,\n        textAlign: &#039;center&#039;,\n        margin: 10,\n    },\n    instructions: {\n        textAlign: &#039;center&#039;,\n        color: &#039;#333333&#039;,\n        marginBottom: 5,\n    },\n    btn: {\n        marginTop: 50,\n        marginLeft: 10,\n        marginRight: 10,\n        width: 200,\n        height: 35,\n        backgroundColor: &#039;#3BC1FF&#039;,\n        color: &#039;#fff&#039;,\n        lineHeight: 24,\n        fontWeight: &#039;bold&#039;,\n        textAlign: &#039;center&#039;,\n        textAlignVertical:&#039;center&#039;\n    },\n});\n\nAppRegistry.registerComponent(&#039;RNAPP&#039;, () =&gt; RNAPP);<\/code><\/pre>\n<h2>\u5b9e\u4f8b\u4e8c\uff1a\u6570\u636e\u4f20\u9012<\/h2>\n<p>\u5b9e\u4f8b\uff1aRN\u8c03\u7528\u539f\u751f\u7684\u754c\u9762\uff0c\u7528\u6237\u64cd\u4f5c\u539f\u751f\u754c\u9762\u540e\u5c06\u7ed3\u679c\u53d1\u9001\u7ed9RN\u4fa7\uff08\u4eceRN\u4fa7\u542f\u52a8Android\u539f\u751f\u7684\u9009\u62e9\u8054\u7cfb\u4eba\u754c\u9762\uff0c\u7528\u6237\u9009\u62e9\u540e\uff0c\u5c06\u5176\u7535\u8bdd\u53f7\u7801\u53d1\u9001\u7ed9RN\u4fa7\uff09<\/p>\n<blockquote>\n<p>\u6ce8\u610f\u5728 AndroidManifest.xml \u4e2d\u6dfb\u52a0\u8bfb\u5199\u901a\u8baf\u5f55\u6743\u9650<\/p>\n<\/blockquote>\n<pre><code class=\"language-xml\">&lt;uses-permission android:name=&quot;android.permission.READ_CONTACTS&quot;\/&gt;\n&lt;uses-permission android:name=&quot;android.permission.WRITE_CONTACTS&quot;\/&gt;<\/code><\/pre>\n<ul>\n<li>\u542f\u52a8\u9009\u62e9\u8054\u7cfb\u4eba<\/li>\n<\/ul>\n<pre><code class=\"language-java\">Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);\nBundle bundle = new Bundle();\ncontext.startActivityForResult(intent, REQUEST_CODE, bundle);<\/code><\/pre>\n<ul>\n<li>\u5904\u7406\u9009\u62e9\u8054\u7cfb\u4eba\u540e\u7684\u7ed3\u679c\uff08onActivityResult\uff09<\/li>\n<\/ul>\n<pre><code class=\"language-java\">public void onActivityResult(int requestCode, int resultCode, Intent data) {\n    super.onActivityResult(requestCode, resultCode, data);\n    if(requestCode!= MyNativeModule.REQUEST_CODE || resultCode!=RESULT_OK)\n        return;\n\n    Uri contactUri = data.getData();\n    Cursor cursor = managedQuery(contactUri, null, null, null, null);\n    cursor.moveToFirst();\n    String phoneNumber = getContactPhone(cursor);\n\n    \/\/\u5c06phoneNumber\u53d1\u9001\u7ed9RN\u4fa7\uff0c\u9700\u8981\u8c03\u7528MyNativeModule\u5bf9\u8c61\u91cc\u9762\u7684\u65b9\u6cd5\n    MainApplication.getMyReactPackage().getMyNativeModule().sendMsgToRn(phoneNumber);\n}<\/code><\/pre>\n<ul>\n<li>\u53d1\u9001\u6d88\u606f\u7ed9RN\u4fa7<\/li>\n<\/ul>\n<pre><code class=\"language-java\">public void sendMsgToRn(String msg) {\n    \/\/\u5c06\u6d88\u606fmsg\u53d1\u9001\u7ed9RN\u4fa7\n    context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(&quot;AndroidToRNMessage&quot;, msg);\n}<\/code><\/pre>\n<p>\u6e90\u7801\uff1a<\/p>\n<p>MyNativeModule.java<\/p>\n<pre><code class=\"language-java\">public class MyNativeModule extends ReactContextBaseJavaModule {\n\n    private ReactApplicationContext context;\n    public static final int REQUEST_CODE = 1;\n\n    public MyNativeModule(ReactApplicationContext reactContext) {\n        super(reactContext);\n        context = reactContext;\n    }\n\n    @Override\n    public String getName() {\n        \/\/\u4e00\u5b9a\u8981\u8fd4\u56de\u4e00\u4e2a\u540d\u5b57\uff0c\u5728RN\u4ee3\u7801\u91cc\u9762\u9700\u8981\u4f7f\u7528\u8fd9\u4e2a\u540d\u5b57\u6765\u8c03\u7528\u8be5\u7c7b\u7684\u65b9\u6cd5\n        return &quot;MyNativeModule&quot;;\n    }\n\n    \/\/\u51fd\u6570\u4e0d\u80fd\u6709\u8fd4\u56de\u503c\uff0c\u56e0\u4e3a\u88ab\u8c03\u7528\u7684\u539f\u751f\u4ee3\u7801\u662f\u5f02\u6b65\u7684\uff0c\u539f\u751f\u4ee3\u7801\u6267\u884c\u7ed3\u675f\u4e4b\u540e\u53ea\u80fd\u901a\u8fc7\u56de\u8c03\u51fd\u6570\u6216\u8005\u53d1\u9001\u6d88\u606f\u7ed9RN\n    \/\/\u5fc5\u987b\u58f0\u660eReactMethod\u6ce8\u89e3\n    @ReactMethod\n    public void showNativeMsg(String msg) {\n        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();\n    }\n\n    \/\/\u5fc5\u987b\u58f0\u660eReactMethod\u6ce8\u89e3\n    @ReactMethod\n    public void newNativePage() {\n        \/*\n        Intent intent = new Intent(context, MyActivity.class);\n        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); \/\/\u5fc5\u987b\u6dfb\u52a0\u8fd9\u6761\u8bed\u53e5\uff0c\u5426\u5219\u62a5\u9519\n        context.startActivity(intent);\n        *\/\n        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);\n        Bundle bundle = new Bundle();\n        context.startActivityForResult(intent, REQUEST_CODE, bundle);\n    }\n\n    public void sendMsgToRn(String msg) {\n        \/\/\u5c06\u6d88\u606fmsg\u53d1\u9001\u7ed9RN\u4fa7\n        context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(&quot;AndroidToRNMessage&quot;, msg);\n    }\n}<\/code><\/pre>\n<p>MainActivity.java<\/p>\n<pre><code class=\"language-java\">public class MainActivity extends ReactActivity {\n\n    \/**\n     * Returns the name of the main component registered from JavaScript.\n     * This is used to schedule rendering of the component.\n     *\/\n    @Override\n    protected String getMainComponentName() {\n        return &quot;AwesomeProject&quot;;\n    }\n\n    @Override\n    public void onActivityResult(int requestCode, int resultCode, Intent data) {\n        super.onActivityResult(requestCode, resultCode, data);\n        if(requestCode!= MyNativeModule.REQUEST_CODE || resultCode!=RESULT_OK)\n            return;\n\n        Uri contactUri = data.getData();\n        Cursor cursor = managedQuery(contactUri, null, null, null, null);\n        cursor.moveToFirst();\n        String phoneNumber = getContactPhone(cursor);\n\n        \/\/\u5c06phoneNumber\u53d1\u9001\u7ed9RN\u4fa7\uff0c\u9700\u8981\u8c03\u7528MyNativeModule\u5bf9\u8c61\u91cc\u9762\u7684\u65b9\u6cd5\n        MainApplication.getMyReactPackage().getMyNativeModule().sendMsgToRn(phoneNumber);\n    }\n\n    private String getContactPhone(Cursor cursor) {\n        int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);\n        int phoneNum = cursor.getInt(phoneColumn);\n        String result = &quot;&quot;;\n        if (phoneNum &gt; 0) {\n            \/\/ \u83b7\u5f97\u8054\u7cfb\u4eba\u7684ID\u53f7\n            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);\n            String contactId = cursor.getString(idColumn);\n            \/\/ \u83b7\u5f97\u8054\u7cfb\u4eba\u7535\u8bdd\u7684cursor\n            Cursor phone = getContentResolver().query(\n                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,\n                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID  + &quot;=&quot; + contactId, null, null);\n            if (phone.moveToFirst()) {\n                for (; !phone.isAfterLast(); phone.moveToNext()) {\n                    int index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);\n                    int typeindex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);\n                    int phoneType = phone.getInt(typeindex);\n                    String phoneNumber = phone.getString(index);\n                    result = phoneNumber;\n                    \/*\n                    switch (phoneType) {\n                    case 2:\n                        result = phoneNumber;\n                        break;\n                    default:\n                         break;\n                    }\n                    *\/\n                }\n                if (!phone.isClosed()) {\n                    phone.close();\n                }\n            }\n        }\n        return result;\n    }\n}<\/code><\/pre>\n<p>MainApplication.java<\/p>\n<pre><code class=\"language-java\">public class MainApplication extends Application implements ReactApplication {\n\n    private static final MyReactPackage myReactPackage = new MyReactPackage();\n\n    public static MyReactPackage getMyReactPackage() {\n        return myReactPackage;\n    }\n\n    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {\n        @Override\n        protected boolean getUseDeveloperSupport() {\n            return BuildConfig.DEBUG;\n        }\n\n        @Override\n        protected List&lt;ReactPackage&gt; getPackages() {\n            return Arrays.&lt;ReactPackage&gt;asList(\n                new MainReactPackage(), myReactPackage\n            );\n        }\n    };\n\n    @Override\n    public ReactNativeHost getReactNativeHost() {\n        return mReactNativeHost;\n    }\n}<\/code><\/pre>\n<p>MyReactPackage.java<\/p>\n<pre><code class=\"language-java\">public class MyReactPackage implements ReactPackage {\n\n    private MyNativeModule myNativeModule;\n\n    public MyNativeModule getMyNativeModule() {\n        return myNativeModule;\n    }\n\n    @Override\n    public List&lt;NativeModule&gt; createNativeModules(ReactApplicationContext reactContext) {\n        List&lt;NativeModule&gt; modules = new ArrayList&lt;&gt;();\n        myNativeModule = new MyNativeModule(reactContext);\n        modules.add(myNativeModule);\n        return modules;\n    }\n\n    @Override\n    public List&lt;Class&lt;? extends JavaScriptModule&gt;&gt; createJSModules() {\n        return Collections.emptyList();\n    }\n\n    @Override\n    public List&lt;ViewManager&gt; createViewManagers(ReactApplicationContext reactContext) {\n        return Collections.emptyList();\n    }\n}<\/code><\/pre>\n<p>index.android.js<\/p>\n<pre><code class=\"language-javascript\">\/**\n * Sample React Native App\n * https:\/\/github.com\/facebook\/react-native\n * @flow\n *\/\n\nimport React, { Component } from &#039;react&#039;;\nimport {\n    AppRegistry,\n    StyleSheet,\n    Text,\n    View,\n    NativeModules,\n    DeviceEventEmitter\n} from &#039;react-native&#039;;\n\nclass RNAPP extends Component {\n    componentWillMount(){\n        DeviceEventEmitter.addListener(&#039;AndroidToRNMessage&#039;, this.handleAndroidMessage);\n    }\n\n    componentWillunMount() {\n        DeviceEventEmitter.remove(&#039;AndroidToRNMessage&#039;, this.handleAndroidMessage);\n    }\n\n    handleAndroidMessage = (msg) =&gt; {\n        console.log(msg);\n        NativeModules.MyNativeModule.showNativeMsg(&#039;\u624b\u673a\u53f7\u7801\u662f\uff1a&#039; + msg + &#039;\\nPowered by RNAPP.CC&#039;);\n    }\n\n    render() {\n        return (\n            &lt;View style={styles.container}&gt;\n                &lt;Text style={styles.welcome}&gt;\n                    Welcome to React Native!\n                &lt;\/Text&gt;\n                &lt;Text style={styles.welcome}&gt;\n                    React Native\u6df7\u5408\u539f\u751f\u5f00\u53d1\n                &lt;\/Text&gt;\n                &lt;Text style={styles.instructions}&gt;\n                    Powered by rnapp.cc\n                &lt;\/Text&gt;\n                &lt;Text onPress={this.newNativePage.bind(this)} style={styles.btn}&gt;\u8c03\u7528\u901a\u8baf\u5f55&lt;\/Text&gt;\n            &lt;\/View&gt;\n        );\n    }\n\n    newNativePage() {\n        NativeModules.MyNativeModule.newNativePage();\n    }\n}\n\nconst styles = StyleSheet.create({\n    container: {\n        flex: 1,\n        justifyContent: &#039;center&#039;,\n        alignItems: &#039;center&#039;,\n        backgroundColor: &#039;#F5FCFF&#039;,\n    },\n    welcome: {\n        fontSize: 20,\n        textAlign: &#039;center&#039;,\n        margin: 10,\n    },\n    instructions: {\n        textAlign: &#039;center&#039;,\n        color: &#039;#333333&#039;,\n        marginBottom: 5,\n    },\n    btn: {\n        marginTop: 50,\n        marginLeft: 10,\n        marginRight: 10,\n        width: 200,\n        height: 35,\n        backgroundColor: &#039;#3BC1FF&#039;,\n        color: &#039;#fff&#039;,\n        lineHeight: 24,\n        fontWeight: &#039;bold&#039;,\n        textAlign: &#039;center&#039;,\n        textAlignVertical:&#039;center&#039;\n    },\n});\n\nAppRegistry.registerComponent(&#039;RNAPP&#039;, () =&gt; RNAPP);<\/code><\/pre>\n<h2>React Native\u6df7\u5408\u539f\u751f\u5f00\u53d1\u4e4bRN\u4e0e\u539f\u751f\u901a\u4fe1\u6269\u5c55\u77e5\u8bc6\u70b9<\/h2>\n<h3>\u56de\u8c03\u51fd\u6570<\/h3>\n<pre><code class=\"language-java\">import com.facebook.react.bridge.Callback;<\/code><\/pre>\n<p>\u7f3a\u70b9\uff1a<\/p>\n<ul>\n<li>\u53ea\u5e94\u5f53\u8c03\u7528\u4e00\u6b21\uff0c\u591a\u6b21\u8c03\u7528\u4f1a\u6709\u4e0d\u53ef\u9884\u671f\u7684\u7ed3\u679c<\/li>\n<li>Android\u4fa7\u65e0\u6cd5\u4e3b\u52a8\u901a\u8fc7\u56de\u8c03\u51fd\u6570\u5411RN\u4fa7\u53d1\u9001\u6d88\u606f<\/li>\n<\/ul>\n<p>\u63a8\u8350\u4f7f\u7528\u6d88\u606f\u673a\u5236\u800c\u4e0d\u662f\u56de\u8c03\u51fd\u6570\uff0c\u53e6\u5916\u5728RN\u4fa7\u5bf9\u5e94\u7684\u56de\u8c03\u51fd\u6570\u4e0d\u4f1a\u7acb\u5373\u6267\u884c\uff0c\u56e0\u4e3a\u6865\u63a5\u673a\u5236\u662f\u5f02\u6b65\u7684\u3002<\/p>\n<pre><code class=\"language-java\">@ReactMethod\npublic void rnCallNativeCallback(Callback errorCallback, Callback successCallback){\n    try {\n        successCallback.invoke(100, 100, 200, 200); \/\/\u8c03\u7528\u56de\u8c03\u51fd\u6570\uff0c\u8fd4\u56de\u7ed3\u679c\n    } catch (IllegalViewOperationException e) {\n        errorCallback.invoke(e.getMessage());\n    }\n}<\/code><\/pre>\n<h3>Promise\u673a\u5236<\/h3>\n<pre><code class=\"language-java\">import com.facebook.react.bridge.Promise;<\/code><\/pre>\n<p>\u5982\u679c\u88ab\u6865\u63a5\u7684\u539f\u751f\u65b9\u6cd5\u7684\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u662f\u4e00\u4e2aPromise\u5bf9\u8c61\uff0c\u90a3\u4e48\u8be5\u65b9\u6cd5\u4f1a\u8fd4\u56de\u4e00\u4e2aJS\u7684Promise\u5bf9\u8c61\u7ed9\u4e0e\u5b83\u5bf9\u5e94\u7684js\u65b9\u6cd5\u3002<\/p>\n<pre><code class=\"language-java\">@ReactMethod\npublic void rnCallNativePromise(String msg, Promise promise) {\n    try {\n        \/\/\u4e1a\u52a1\u903b\u8f91\u5904\u7406\n        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();\n        String componentName = getCurrentActivity().getComponentName().toString();\n        promise.resolve(componentName);\n    }catch (Exception e){\n        promise.reject(&quot;100&quot;, e.getMessage()); \/\/Promise \u5931\u8d25\n    }\n}<\/code><\/pre>\n<h3>\u8de8\u8bed\u8a00\u5e38\u91cf<\/h3>\n<p>\u4e3a\u4e86\u4fdd\u6301Android\u4fa7\u4e0eRN\u4fa7\u5e38\u91cf\u7684\u4e00\u81f4\u6027\uff0c\u53ef\u4ee5\u5c06Android\u539f\u751f\u4ee3\u7801\u7684\u5e38\u91cf\u66b4\u9732\u7ed9RN\u4fa7\u3002\u5728MyNativeModule\u7c7b\u4e2d\u590d\u5199getConstants()\uff0c\u5728RN\u4fa7\u4f7f\u7528NativeModules.MyNativeModule.author<\/p>\n<pre><code class=\"language-java\">@Nullable\n@Override\npublic Map&lt;String, Object&gt; getConstants() {\n    final Map&lt;String, Object&gt; constants = new HashMap&lt;&gt;();\n    constants.put(&quot;URL&quot;, &quot;http:\/\/www.appblog.cn\/&quot;);\n    constants.put(&quot;port&quot;, &quot;8081&quot;);\n    constants.put(&quot;ip&quot;, &quot;192.168.1.100&quot;);\n    constants.put(&quot;author&quot;, &quot;AppBlog.CN&quot;);\n    return constants;\n}<\/code><\/pre>\n<pre><code class=\"language-xml\">&lt;Text style={styles.instructions}&gt;\n    URL: {NativeModules.MyNativeModule.URL}\n&lt;\/Text&gt;\n&lt;Text style={styles.instructions}&gt;\n    Author: {NativeModules.MyNativeModule.author}\n&lt;\/Text&gt;<\/code><\/pre>\n<h3>\u591a\u7ebf\u7a0b\u673a\u5236<\/h3>\n<p>\u5982\u679c\u539f\u751f\u4ee3\u7801\u6a21\u5757\u6267\u884c\u9700\u8981\u8f83\u957f\u7684\u65f6\u95f4\uff0c\u5e94\u5f53\u81ea\u5df1\u542f\u52a8\u4e00\u4e2a\u7ebf\u7a0b\u5e76\u5728\u7ebf\u7a0b\u4e2d\u6267\u884c\uff01\u6700\u540e\u901a\u8fc7\u56de\u8c03\u65b9\u6cd5\u8fdb\u884c\u83b7\u53d6\u6267\u884c\u7ed3\u679c\u5373\u53ef\u3002<\/p>\n<p>Android\u4e2dUI\u7b49\u5f85\u65f6\u95f4\u8fc7\u957f\u4f1a\u62a5ANR\u5f02\u5e38\u3002<\/p>\n<h3>\u76d1\u542cActivityResult\u4e0eAndroid\u751f\u547d\u5468\u671f\u4e8b\u4ef6<\/h3>\n<pre><code class=\"language-java\">implements ActivityEventListener, LifecycleEventListener<\/code><\/pre>\n<pre><code class=\"language-java\">\/\/\u589e\u52a0\u76d1\u542c\uff0c\u8ba9\u5f53\u524d\u7c7b\u7684onActivityResult\u5904\u7406\u8fd4\u56de\ncontext.addActivityEventListener(this);\n\/\/\u5728\u6784\u9020\u51fd\u6570\u4e2d\u6ce8\u518c\u751f\u547d\u5468\u671f\u4e8b\u4ef6\u7684\u76d1\u542c\u63a5\u53e3\ncontext.addLifecycleEventListener(this);<\/code><\/pre>\n<p>\u5982\u679c\u6211\u4eec\u9700\u8981\u76d1\u542cActivity\u7684\u751f\u547d\u5468\u671f\uff0c\u4f8b\u5982nResume\u3001onPause\u7b49\u7b49\u65b9\u6cd5\uff0c\u5982\u679c\u8981\u5b9e\u73b0\u8fd9\u6837\u7684\u529f\u80fd\uff0c\u90a3\u4e48\u5f53\u524d\u6a21\u5757\u7c7b\u9700\u8981\u5b9e\u73b0LifcycleEventListener\u63a5\u53e3\u5e76\u4e14\u5728\u8be5\u6a21\u5757\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e2d\u8fdb\u884c\u6ce8\u518c\u8be5\u63a5\u53e3\u3002<\/p>\n<h4>ActivityEventListener \u63a5\u53e3\u65b9\u6cd5<\/h4>\n<ul>\n<li><code>void onActivityResult(int requestCode, int resultCode, Intent data)<\/code><\/li>\n<li><code>void onNewIntent(Intent intent)<\/code><\/li>\n<\/ul>\n<h4>LifecycleEventListener \u63a5\u53e3\u65b9\u6cd5<\/h4>\n<ul>\n<li><code>void onHostResume()<\/code><\/li>\n<li><code>void onHostPause()<\/code><\/li>\n<li><code>void onHostDestroy()<\/code><\/li>\n<\/ul>\n<h3>\u521d\u59cb\u542f\u52a8\u7684Activity\u8bbe\u5b9a<\/h3>\n<p>\u5728AndroidManifest.xml\u6587\u4ef6\u4e2d \u5e26<code>intent-filter<\/code>\u7684Activity \u53ef\u4ee5\u8bbe\u5b9a\u5f00\u59cb\u542f\u52a8\u7684activity\u662fRN\u7684\u8fd8\u662f\u539f\u751f\u7684<\/p>\n<h3>\u6e90\u7801<\/h3>\n<p>MyNativeModule.java<\/p>\n<pre><code class=\"language-java\">public class MyNativeModule extends ReactContextBaseJavaModule implements ActivityEventListener, LifecycleEventListener {\n\n    private ReactApplicationContext context;\n    public static final int REQUEST_CODE = 1;\n\n    public MyNativeModule(ReactApplicationContext reactContext) {\n        super(reactContext);\n        context = reactContext;\n        \/\/\u589e\u52a0\u76d1\u542c\uff0c\u8ba9\u5f53\u524d\u7c7b\u7684onActivityResult\u5904\u7406\u8fd4\u56de\n        context.addActivityEventListener(this);\n        \/\/\u5728\u6784\u9020\u51fd\u6570\u4e2d\u6ce8\u518c\u751f\u547d\u5468\u671f\u4e8b\u4ef6\u7684\u76d1\u542c\u63a5\u53e3\n        context.addLifecycleEventListener(this);\n    }\n\n    @Override\n    public String getName() {\n        \/\/\u4e00\u5b9a\u8981\u8fd4\u56de\u4e00\u4e2a\u540d\u5b57\uff0c\u5728RN\u4ee3\u7801\u91cc\u9762\u9700\u8981\u4f7f\u7528\u8fd9\u4e2a\u540d\u5b57\u6765\u8c03\u7528\u8be5\u7c7b\u7684\u65b9\u6cd5\n        return &quot;MyNativeModule&quot;;\n    }\n\n    \/\/\u51fd\u6570\u4e0d\u80fd\u6709\u8fd4\u56de\u503c\uff0c\u56e0\u4e3a\u88ab\u8c03\u7528\u7684\u539f\u751f\u4ee3\u7801\u662f\u5f02\u6b65\u7684\uff0c\u539f\u751f\u4ee3\u7801\u6267\u884c\u7ed3\u675f\u4e4b\u540e\u53ea\u80fd\u901a\u8fc7\u56de\u8c03\u51fd\u6570\u6216\u8005\u53d1\u9001\u6d88\u606f\u7ed9RN\n    \/\/\u5fc5\u987b\u58f0\u660eReactMethod\u6ce8\u89e3\n    @ReactMethod\n    public void showNativeMsg(String msg) {\n        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();\n    }\n\n    \/\/\u5fc5\u987b\u58f0\u660eReactMethod\u6ce8\u89e3\n    @ReactMethod\n    public void rnCallNative() {\n        \/*\n        Intent intent = new Intent(context, MyActivity.class);\n        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); \/\/\u5fc5\u987b\u6dfb\u52a0\u8fd9\u6761\u8bed\u53e5\uff0c\u5426\u5219\u62a5\u9519\n        context.startActivity(intent);\n        *\/\n        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);\n        Bundle bundle = new Bundle();\n        context.startActivityForResult(intent, REQUEST_CODE, bundle);\n    }\n\n    public void sendMsgToRn(String msg) {\n        \/\/\u5c06\u6d88\u606fmsg\u53d1\u9001\u7ed9RN\u4fa7\n        context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(&quot;AndroidToRNMessage&quot;, msg);\n    }\n\n    @ReactMethod\n    public void rnCallNativeCallback(Callback errorCallback, Callback successCallback){\n        try {\n            successCallback.invoke(100, 100, 200, 200); \/\/\u8c03\u7528\u56de\u8c03\u51fd\u6570\uff0c\u8fd4\u56de\u7ed3\u679c\n        } catch (IllegalViewOperationException e) {\n            errorCallback.invoke(e.getMessage());\n        }\n    }\n\n    @ReactMethod\n    public void rnCallNativePromise(String msg, Promise promise) {\n        try {\n            \/\/\u4e1a\u52a1\u903b\u8f91\u5904\u7406\n            Toast.makeText(context, msg, Toast.LENGTH_LONG).show();\n            String componentName = getCurrentActivity().getComponentName().toString();\n            promise.resolve(componentName);\n        }catch (Exception e){\n            promise.reject(&quot;100&quot;, e.getMessage()); \/\/Promise \u5931\u8d25\n        }\n    }\n\n    @Nullable\n    @Override\n    public Map&lt;String, Object&gt; getConstants() {\n        final Map&lt;String, Object&gt; constants = new HashMap&lt;&gt;();\n        constants.put(&quot;URL&quot;, &quot;http:\/\/www.rnapp.cc\/&quot;);\n        constants.put(&quot;port&quot;, &quot;8081&quot;);\n        constants.put(&quot;ip&quot;, &quot;192.168.1.100&quot;);\n        constants.put(&quot;author&quot;, &quot;RNAPP.CC&quot;);\n        return constants;\n    }\n\n    @Override\n    public void onActivityResult(int requestCode, int resultCode, Intent data) {\n        Log.i(TAG, &quot;requestCode=&quot; + requestCode + &quot;, resultCode=&quot; + resultCode);\n        if (requestCode!=REQUEST_CODE || resultCode!=RESULT_OK)\n            return;\n        Log.i(TAG, &quot;\u5728\u539f\u751f\u6a21\u5757\u7c7b\u91cc\u5b9e\u73b0\u76d1\u542c\u63a5\u53e3ActivityEventListener&quot;);\n        sendMsgToRn(&quot;\u5728\u539f\u751f\u6a21\u5757\u7c7b\u91cc\u5b9e\u73b0\u76d1\u542c\u63a5\u53e3ActivityEventListener&quot;);\n    }\n\n    @Override\n    public void onNewIntent(Intent intent) {\n\n    }\n\n    @Override\n    public void onHostResume() {\n        Log.i(TAG, &quot;onActivityResume&quot;);\n    }\n\n    @Override\n    public void onHostPause() {\n        Log.i(TAG, &quot;onActivityPause&quot;);\n    }\n\n    @Override\n    public void onHostDestroy() {\n        Log.i(TAG, &quot;onActivityDestroy&quot;);\n    }\n}<\/code><\/pre>\n<p>index.android.js<\/p>\n<pre><code class=\"language-javascript\">\/**\n * Sample React Native App\n * https:\/\/github.com\/facebook\/react-native\n * @flow\n *\/\n\nimport React, { Component } from &#039;react&#039;;\nimport {\n    AppRegistry,\n    StyleSheet,\n    Text,\n    View,\n    NativeModules,\n    DeviceEventEmitter\n} from &#039;react-native&#039;;\n\nclass RNAPP extends Component {\n    componentWillMount(){\n        DeviceEventEmitter.addListener(&#039;AndroidToRNMessage&#039;, this.handleAndroidMessage);\n    }\n\n    componentWillunMount() {\n        DeviceEventEmitter.remove(&#039;AndroidToRNMessage&#039;, this.handleAndroidMessage);\n    }\n\n    handleAndroidMessage = (msg) =&gt; {\n        console.log(msg);\n        NativeModules.MyNativeModule.showNativeMsg(&#039;\u8fd4\u56de\uff1a&#039; + msg + &#039;\\nPowered by RNAPP.CC&#039;);\n    }\n\n    render() {\n        return (\n            &lt;View style={styles.container}&gt;\n                &lt;Text style={styles.welcome}&gt;\n                    Welcome to React Native!\n                &lt;\/Text&gt;\n                &lt;Text style={styles.welcome}&gt;\n                    React Native\u6df7\u5408\u539f\u751f\u5f00\u53d1\n                &lt;\/Text&gt;\n                &lt;Text style={styles.instructions}&gt;\n                    Powered by rnapp.cc\n                &lt;\/Text&gt;\n                &lt;Text onPress={this.callNative.bind(this)} style={styles.btn}&gt;\u8c03\u7528\u539f\u751f\u51fd\u6570 - \u6d88\u606f\u673a\u5236&lt;\/Text&gt;\n                &lt;Text onPress={this.callNativeCallback.bind(this)} style={styles.btn}&gt;\u8c03\u7528\u539f\u751f\u51fd\u6570 - \u56de\u8c03\u51fd\u6570&lt;\/Text&gt;\n                &lt;Text onPress={this.callNativePromise.bind(this)} style={styles.btn}&gt;\u8c03\u7528\u539f\u751f\u51fd\u6570 - Promise&lt;\/Text&gt;\n                &lt;Text style={styles.welcome} &gt;\n                    Android\u539f\u751f\u66b4\u9732\u7684\u5e38\u91cf\n                &lt;\/Text&gt;\n                &lt;Text style={styles.instructions}&gt;\n                    URL: {NativeModules.MyNativeModule.URL}\n                &lt;\/Text&gt;\n                &lt;Text style={styles.instructions}&gt;\n                    Author: {NativeModules.MyNativeModule.author}\n                &lt;\/Text&gt;\n            &lt;\/View&gt;\n        );\n    }\n\n    callNative() {\n        NativeModules.MyNativeModule.rnCallNative();\n    }\n\n    callNativeCallback = () =&gt; {\n        NativeModules.MyNativeModule.rnCallNativeCallback(\n            (msg) =&gt; {\n                console.log(msg);\n            },\n            (x, y, width, height) =&gt; {\n                console.log(&#039;\u5750\u6807: (&#039; + x + &#039;,&#039; + y + &#039;), \u5bbd: &#039; + width + &#039;, \u9ad8: &#039; + height);\n                NativeModules.MyNativeModule.showNativeMsg(&#039;\u5750\u6807: (&#039; + x + &#039;,&#039; + y + &#039;), \u5bbd: &#039; + width + &#039;, \u9ad8: &#039; + height);\n            }\n        );\n    }\n\n    callNativePromise = () =&gt; {\n        NativeModules.MyNativeModule.rnCallNativePromise(&#039;React Native Promise\u673a\u5236\u8c03\u7528\u539f\u751f\u6a21\u5757\u7684\u65b9\u6cd5&#039;).then(\n            (msg) =&gt; {\n                console.log(&#039;Promise\u6210\u529f\uff1a&#039; + msg);\n            }\n        ).catch(\n            (err) =&gt; {\n                console.log(err);\n            }\n        );\n    }\n}\n\nconst styles = StyleSheet.create({\n    container: {\n        flex: 1,\n        justifyContent: &#039;center&#039;,\n        alignItems: &#039;center&#039;,\n        backgroundColor: &#039;#F5FCFF&#039;,\n    },\n    welcome: {\n        fontSize: 20,\n        textAlign: &#039;center&#039;,\n        margin: 10,\n    },\n    instructions: {\n        textAlign: &#039;center&#039;,\n        color: &#039;#333333&#039;,\n        marginBottom: 5,\n    },\n    btn: {\n        marginTop: 20,\n        marginLeft: 10,\n        marginRight: 10,\n        width: 260,\n        height: 35,\n        backgroundColor: &#039;#3BC1FF&#039;,\n        color: &#039;#fff&#039;,\n        lineHeight: 24,\n        fontWeight: &#039;bold&#039;,\n        textAlign: &#039;center&#039;,\n        textAlignVertical:&#039;center&#039;\n    },\n});\n\nAppRegistry.registerComponent(&#039;RNAPP&#039;, () =&gt; RNAPP);<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>React Native\u4e0e\u539f\u751f\u901a\u4fe1\uff0c\u672c\u6587\u9002\u914dAndroid\u539f\u751f\u4e0eRN\u7684\u6df7\u5408\u5f00\u53d1 \u5b9e\u4f8b\u4e00\uff1a\u9875\u9762\u8df3\u8f6c RN\u89e6\u53d1An [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[163],"tags":[],"class_list":["post-517","post","type-post","status-publish","format-standard","hentry","category-react-native"],"_links":{"self":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/517","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/comments?post=517"}],"version-history":[{"count":0,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/517\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/media?parent=517"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/categories?post=517"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/tags?post=517"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}