android - 将 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{
}
}
解决方案
尝试这个
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*/
);
也请阅读以更好地理解
推荐阅读
- javascript - 使用纯 JavaScript 从 Firestore 接收数据
- excel - VBa和Excel:总结特定项目编号中突出显示的单元格值,然后从其他表中减去单元格值并显示在下一列
- java - 我的 Comparator 类中出现奇怪的错误,eclipse 称它为语法,但语法似乎正确
- python - 在 python 美汤和熊猫中填补缺失的日期
- python - 是否有任何理由在完全兼容 Python 3 的代码中使用“from __future__ import print_function”?
- scala - 如何在scala中对类(不是类类型)的变量进行instanceOf
- sql - SQL 平面表中的分组
- python-3.x - Python Gtk+3 教程 23 应用程序没有显示预期的内容?
- swift - 从 Firestore 获取一个空数组,尽管它不是 nil
- performance - Elasticsearch:有没有办法关闭评分以提高性能?