Nikesh Kerkar
Nikesh Kerkar

Reputation: 31

How to return data from activity to Cordova plugin

I have written Cordova plugin to call a Cordova activity

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.

Upvotes: 3

Views: 1917

Answers (3)

Rohit Singh
Rohit Singh

Reputation: 18202

All CordovaPlugin comes with Callback by default

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.

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);
        
       }
    }

}

Upvotes: 0

androiddeveloper2011
androiddeveloper2011

Reputation: 226

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. It's working perfectly

Upvotes: 1

Roope Hakulinen
Roope Hakulinen

Reputation: 7405

See the Android platform guide on Cordova documentation. 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.

Also if you want to indicate that error happened, you can call

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

Upvotes: 0

Related Questions