startActivityForResult在android studio中迁移到android后文件上传器显示错误.&


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

这是文件从webviewactivity.java上传到我的android应用程序的代码。我已经在android studio中更新了我的应用程序到androidX。它向我显示了一个错误,startActivityForResult()是过时的函数,我必须使用registerForActivityResult()代替。我已经修复了升级到androidX后产生的所有问题。可能是因为我是一个初级android开发人员,我无法理解我如何解决这个问题,我也检查了developer.android.com文档的registerForActivityResult()函数,但我无法理解我如何在这里使用它并修复问题,因为显示是android工作室。

任何前辈的帮助都是值得感激的。我还编译了应用程序,忽略了在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

最新更新