首页 > 解决方案 > 将 java 变量从 javacode 传递到 react-native 中的 javascript 代码

问题描述

我想将通过 Android 代码中 MainActivity.java 文件中的 Intents 接收到的图像和文本传递并显示到我在 react-native 中的 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{

          }
    }

标签: androidreact-nativereact-native-android

解决方案


尝试这个

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*/
);

阅读以更好地理解


推荐阅读