如何从 android Activity onActivityResult 发送 object/string 以响应本机

how to Send object/string from android Activity onActivityResult to react native

在我的 react native 项目中,我已经在 android 中实现了支付原生 sdk(在 react native 中不支持)。所以我试图用原生模块调用原生 sdk..

我可以从 React Native Native 模块调用支付 SDKUI,但是当结果时间无法将结果发送回 React Native 组件时..

支付网关是 -> PAYUBIZ

更多详情请查看下面的代码..

在支付网关的末尾,我在 android 本地警报中显示了支付响应..

使用代码..

1. Created NATIVE MODULES in react native side..



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

        in button action following code to call native method from android
        PayUBizAccess.showPayuBiz();

2. Created ReactContextBaseJavaModule based PayUBizModule



@ReactMethod
  public void showPayuBiz() {

    final Activity activity = getCurrentActivity();


    Intent intent = new Intent(activity, PayuActivity.class);


    getReactApplicationContext().startActivity(intent);
   }

PayuActivity.class is the payment activity class

3. Display results after payment success or failure..



     @Override
            public void onActivityResult(int requestCode, int resultCode, final Intent data) {



                if (requestCode == PayuConstants.PAYU_REQUEST_CODE) {
                    if (data != null) {


                        new AlertDialog.Builder(this)
                                .setCancelable(false)
                                .setMessage("Payu's Data : " + data.getStringExtra("payu_response") + "\n\n\n Merchant's Data: " + data.getStringExtra("result"))
                                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        dialog.dismiss();
                                        finish();
                                    }
                                }).show();

                    } else {
                        Toast.makeText(this, getString(R.string.could_not_receive_data), Toast.LENGTH_LONG).show();
                    }
                }
            }

4. After alert clicking button in alert it directly moves to react native component..

所以现在我想要结果数据对本机做出反应,请向我提出任何解决方案

提前致谢

您可以像这样从本机代码发送事件:

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

并且在你的本机代码中你可以接收这样的事件:

componentWillMount: function() {
   DeviceEventEmitter.addListener('keyboardWillShow', function(e: Event) {
  // handle event.
});

}

查看完整文档here

给出了另一种方法here

我建议使用 promise。
在您的本机模块中有一个 属性 作为 Promise mPromise;(也包括 import com.facebook.react.bridge.Promise;) 并在你的本机反应方法中接受承诺

@ReactMethod
public void showPayuBiz(Promise promise) {
  mPromise = promise;
  final Activity activity = getCurrentActivity();
  Intent intent = new Intent(activity, PayuActivity.class);
  getReactApplicationContext().startActivity(intent);
}

并且在您的 onActivityResult 中,您可以按如下方式使用它。

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) 
{
  if (requestCode == PayuConstants.PAYU_REQUEST_CODE) {
    //example for handling success response
    this.promise.resolve(data.getDataString()); // you can further process this data in react native component.
  }
  else{
    //example for handling error response
    this.promise.reject(data.getDataString());
  }
}

那么就可以如下使用了

PayUBizAccess.showPayuBiz()
    .then(data => {
      console.log(data);
      //success 
    })
    .catch(error => {
      console.log(data);
      //failure
    });

编辑

如果onActivityResult()在另一个文件中。在 MainActivity.

中的 onActivityResult() 中添加 mReactInstanceManager.onActivityResult(requestCode, resultCode, data);

在你的原生模块中,添加以下方法。

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    this.mPromise.resolve(data.getDataString());
}

我使用了@Ayush Khare 的回复..在调试时遇到了一些问题..所以我post在这里给出了确切的答案

1.React Native Side

Component will mount add following

    DeviceEventEmitter.addListener('PAYUEVENT', this.payuResponseGet);debugger

Add following method for trigger event

payuResponseGet = (payUData) => {
    console.log(payUData);debugger // logging twice
    // this.setState({
    //   modalVisible: args.visible
    // })
  }

2. Activity side

import com.facebook.react.ReactInstanceManager;
//import com.facebook.react.ReactApplicationContext;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.modules.core.DeviceEventManagerModule;


Add following on result method
//  mPromise.resolve(data.getDataString());
 ReactInstanceManager mReactInstanceManager = getReactNativeHost().getReactInstanceManager();
 ReactApplicationContext context = (ReactApplicationContext) mReactInstanceManager.getCurrentReactContext();

 WritableMap payuData = Arguments.createMap();
        payuData.putString("PayuResponses", data.getStringExtra("payu_response"));
        payuData.putString("Merchant's Data", data.getStringExtra("result"));

 sendEvent(context,"PAYUEVENT",payuData);

//send event method
private void sendEvent(ReactContext reactContext,
                   String eventName,
                   @Nullable WritableMap params) {
  reactContext
    .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
    //supply the result in params
    .emit(eventName, params);
}

在上面添加后,运行 并从触发事件方法中获取响应..