java - 在 android studio 中迁移到 android 后,文件上传器中的 startActivityForResult 显示错误
问题描述
//File manager
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams) {
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(WebviewActivity.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
这是从我的 android 应用程序中的 webviewactivity.java 上传的文件的代码。在我在 android studio 中将我的应用程序更新为 androidX 之后。它向我显示了一个错误,即 startActivityForResult() 已被弃用,我必须改用 registerForActivityResult() 。我已经修复了升级到 androidX 后产生的所有问题。可能是因为我是一名初级 android 开发人员,我不明白如何解决这个问题如图所示是android studio。
任何一位前辈的善意帮助都是值得的。我还编译了该应用程序,忽略了在 android studio 中显示的这个问题,该问题在我的具有 API 级别 24 的智能手机中编译和工作,不确定文件上传是否可以在 API 级别 29、30、31 的手机上工作。为了您的更多信息,我无法使用虚拟设备,因为我的笔记本电脑资源太低而无法使用 AVD。
谢谢。
解决方案
ActivityResultLauncher<String> mGetContent;//declare
mGetContent
通过调用以下函数进行初始化
private void initializePicker(){
mGetContent =
registerForActivityResult(new ActivityResultContracts.GetContent(),
uri -> {
if(uri!=null) {
noticeUri = uri;
//do your work here or
//save the uri in global variable for future use
}
else{
Toast.makeText(CROption.this, "No file selected", Toast.LENGTH_SHORT).show();
}
});
}
使用以下行开始选择器:
mGetContent.launch("application/pdf")//allow to select only pdf files
推荐阅读
- python - (sqlite3.IntegrityError) NOT NULL 约束失败:surfers.id
- c++ - 如何将位集拆分为数组
- scala - 如何将通用测试配置应用于所有项目?
- node.js - 在 JSON 中附加每个元素的坐标
- python - 在 Python 中是否有可能有一个函数来创建许多具有递增更改名称的新变量
- c++ - 从 txt 文件初始化 uint8_t 数组
- c++ - 转换函数,std::is_base_of 和虚假的不完整类型:替换失败是一个错误
- url - 什么时候一个字符等同于它在 URL 中的百分比编码版本?
- javafx - 将 CheckBox 列添加到现有的 TableView
- android - 如何在 Android 上获取日历提醒