简体   繁体   English

如何从活动返回数据到Cordova插件

[英]How to return data from activity to Cordova plugin

I have written Cordova plugin to call a Cordova activity我写了 Cordova 插件来调用 Cordova 活动

Intent intent=new Intent(cordova.getActivity() , AndroidCamera.class);
cordova.getActivity().startActivity(intent);

I want to return some data from this Android camera activity to my plugin so I can send back it to JavaScript.我想从这个 Android 相机活动中返回一些数据到我的插件,这样我就可以将它发送回 JavaScript。

call your activity in Activity for result,在活动中调用您的活动以获得结果,

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "*****  result from camera" + requestCode + " *****  " + resultCode);
        if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
            if (bitmap != null) {
                     callbackContext.success(base64Image);
              }
        }

I am converting Bitmap into Base64 image and sending to server via success method.我正在将 Bitmap 转换为 Base64 图像并通过成功方法发送到服务器。 It's working perfectly它工作完美

See the Android platform guide on Cordova documentation.请参阅 Cordova 文档中的Android 平台指南 There is nice example that echos the message back.有一个很好的例子可以回显消息。

callbackContext.success(message);

where callbackContext is the CallbackContext provided as parameter for execute of your plugin.其中 callbackContext 是作为执行插件的参数提供的 CallbackContext。

Also if you want to indicate that error happened, you can call此外,如果您想表明发生了错误,您可以致电

callbackContext.error("Expected one non-empty string argument.");

All CordovaPlugin comes with Callback by default所有 CordovaPlugin 默认都自带 Callback

If you are making a CordovaPlugin you extends CordovaPlugin class. CordovaPlugin class comes with onActivityResult(int requestCode, int resultCode, Intent intent) method which you can override in your plugin to get result.如果您正在制作 CordovaPlugin,您可以扩展CordovaPlugin CordovaPlugin class 带有onActivityResult(int requestCode, int resultCode, Intent intent)方法,您可以在插件中覆盖该方法以获得结果。

Here is a generic Code Sample这是一个通用的代码示例

public class MyCordovaPlugin extends CordovaPlugin{

     private int MY_REQ_CODE = 1000;

     public void someMethod(){
          Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
          cordova.getActivity()startActivityForResult(takePictureIntent, MY_REQ_CODE);
     }

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

       if (requestCode == MY_REQ_CODE) {
           // Do you thing with Data
           log.d("MY_TAG", data);
        
       }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM