20160907

React Native 里需要接入友盟推送,首先按照官方文档在Android Studio里导入推送Module依赖,然后在MainApplication里添加PushSDK服务,处理通知

 private void initPushSDk() {
    PushAgent mPushAgent = PushAgent.getInstance(getApplicationContext());
    mPushAgent.enable();
    mPushAgent.setNotificationClickHandler(notificationClickHandler);

}

private static final String a = UmengNotificationClickHandler.class.getName();
//友盟通知自定义点击处理
UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler(){
    @Override
    public void dealWithCustomAction(Context context, UMessage msg) {
        launchApplication(context,msg);//先启动后台应用
        WritableMap params = Arguments.createMap();
        String custom = msg.custom;
        params.putString("custom",custom);
        Log.e("custome",custom);
        ReactContext reactContext = getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
        sendEvent(reactContext, "umeng_notification", params);
    }
};

private void launchApplication(Context context,UMessage msg){
    Intent var3 = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    if(var3 == null) {
        com.umeng.common.message.Log.b(a, "handleMessage(): cannot find app: " + context.getPackageName());
    } else {
        var3.setPackage((String) null);
        var3.addFlags(268435456);
        context.startActivity(var3);
    }
}

private  void sendEvent(ReactContext reactContext,
                              String eventName,
                              @Nullable WritableMap params) {
    reactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, params);
}

React Native 主页面里监听原生里发送的事件,跳转到相应的界面:

componentDidMount() {
    if (Platform.OS === 'android') {
          BackAndroid.addEventListener('hardwareBackPress', () => this.onBackAndroid());
    };
    DeviceEventEmitter.addListener('umeng_notification', (e: Event) => {
      //e为原生传递过来的参数e.custom
    this.navigator.push({
        component: ShowNotificationPage
      });
      });
  }

可能是生命周期的原因,当android回退键退出应用时,只能拉起App却无法跳转到相应的界面,因此我在回退键的事件处理上进行了拦截,让App movebacktostack,而不是让界面销毁掉,相当于Home键的功能。

React Native组件之间通信一般是通过props就可以实现父控件向子控件传值,父控件获取子控件的值.
也可以通过React Native 中的DeviceEventEmitter处理组件之间的监听事件,方式如下:

componentWillUnmount() {  
    this.subscription.remove();
  }

  componentDidMount() {  
    this.subscription = DeviceEventEmitter.addListener('followChanged', () => {
          this.onRefresh()
        });

    this.onRefresh();
  }

  onRefresh() {
        this.reuqestFans(this.props.mid);
  }

其他组件触发事件:

DeviceEventEmitter.emit('followChanged');