美文网首页
在Android中实现RN的自定义Native Modeule

在Android中实现RN的自定义Native Modeule

作者: VictorLiang | 来源:发表于2017-03-19 15:55 被阅读288次

RN中想从JS调用Native中方法时,一般都需要通过自定义Native Module的方式来实现,下面来看一下如何在Android中实现一个自定义的Module。

Step 1

继承ReactContextBaseJavaModule,实现它的getName方法。
name用来以后Module的使用。

public class UserCenterAndroidModule extends ReactContextBaseJavaModule {

    public UserCenterAndroidModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "UserCenterAndroid";
    }

Step 2

添加要暴露的方法,并 添加 @ReactMethod 注解。

@ReactMethod
    public boolean hasUserLogin() {
        return UserInfoSharedPreference.getUserStatus(getReactApplicationContext()) != UserStatusUtil.USER_STATUS_UNLOGIN;
    }

需要注意的是支持的方法参数类型与JS中类型的对应关系:

Boolean -> Bool
Integer -> Number
Double -> Number
Float -> Number
String -> String
Callback -> function
ReadableMap -> Object
ReadableArray -> Array

Step 3

在Android工程中注册Module。

public class UserCenterReactPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new UserCenterAndroidModule(reactContext));
        return modules;
    }

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

在ReactInstanceManager的实例中添加Module。

reactRootView = new ReactRootView(getActivity());
//ReactInstanceManager最好是单例的
reactInstanceManager = ReactInstanceManager.builder()
        .setApplication(getActivity().getApplication())
        .setBundleAssetName("index.android.bundle")
        .setJSMainModuleName("index.android")
        .addPackage(new MainReactPackage())
        .addPackage(new UserCenterReactPackage())
        .setUseDeveloperSupport(BuildConfig.DEBUG)
        .setInitialLifecycleState(LifecycleState.RESUMED)
        .build();

Step 4

为了方便使用,一般建议把这个NativeModule封装成一个JS Module。

我们建一个UserCenterAndroid的JS Module(其实就是UserCenterAndroid.js 喽)。

import { NativeModules } from 'react-native';
module.exports = NativeModules.UserCenterAndroid;

Step 5

现在可以在JS代码中轻易的使用这个JS Module(对用的实现就是自定义Native Module)了。

import UserCenterAndroid from './UserCenterAndroid';
var hasUserLogin = UserCenterAndroid.hasUserLogin();

到此,Android中成功添加自定义Native Module。

相关文章

网友评论

      本文标题:在Android中实现RN的自定义Native Modeule

      本文链接:https://www.haomeiwen.com/subject/ywomnttx.html