将java变量从javacode传递给react-native中的javascript代码

时间:2018-05-08 08:35:09

标签: android react-native react-native-android

我想通过android代码中的MainActivity.java文件中的Intents传递并显示通过Intent接收的图像和文本到本地的JavaScript文件中。

以下是通过我的MainActivity.java文件代码中的意图获取数据的代码

@Override
  protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();

        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if ("text/plain".equals(type)) {
                handleSendText(intent); 
            } else if (type.startsWith("image/")) {
                setContentView(R.layout.activity_main);
                imageView = (ImageView) findViewById(R.id.sentImage);
                handleSendImage(intent);
            } 
        }else {
            // Handle other intents, such as being started from the home screen
        }
    }


  void handleSendText(Intent intent) {
          String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
           if (sharedText != null) {
             AlertDialog.Builder builder = new AlertDialog.Builder(context);
             builder.setMessage(sharedText);
             AlertDialog alertDialog = builder.create();
             alertDialog.show();
           }
   }

   void handleSendImage(Intent intent) {
        Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
          if (imageUri != null) {
            imageView.setImageURI(imageUri);
          }else{

          }
    }

1 个答案:

答案 0 :(得分:1)

试试这个

import com.facebook.react.bridge.Callback;


// a callback is used to provide the function call result to JavaScript.

@ReactMethod
public void getImageNText(Callback successCallback,Callback errorCallback)

{
try{

  //Do your stuff here 
  // let say result of text is storedin respText and image in respImg
  // to send it to Javascript side 
  successCallback.invoke(respText,respImg);
 }catch(Exception e){
  errorCallback.invoke(e.getMessage());
}



}

现在在javascript端阅读

"YourModuleName".getImageNText(

(text,image) => {/*successCallback*/
// do your stuff with image and 
},
(error) => {// handle error} ///*errorCallback*/
);

同时为this提供阅读以便更好地理解