我将下载的电子表格中的数据导入Room数据库。这就是我需要做的:
String filePath = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath();
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
try {
FileInputStream stream = new FileInputStream(importFile);
// do stuff
} catch (Exception e1) {e1.printStackTrace();}
所以,这已经不起作用了(?(我还没能找到一个简洁的解释(用JAVA(,说明如何在不请求MANAGE_EXTERNAL_STORAGE权限的情况下完成这个简单的操作(这是一个不可接受的解决方案(大师的帮助?
因此,需要在manifest中设置intent,并为遗留的android 保留旧权限
清单:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<application
android:requestLegacyExternalStorage="true"
>
<activity
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
在mainActivity中,设置文件选取器,创建方法以启动选取器,并创建方法以处理选取器结果。
主要活动:
private ActivityResultLauncher<Intent> launchFilePicker;
public File importFile;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).
getAbsolutePath();
launchFilePicker = registerForActivityResult(
new ActivityResultContract<Intent, Uri>() {
@NonNull
@Override
public Intent createIntent(@NonNull Context context, Intent input) {
return input;
}
@Override
public Uri parseResult(int resultCode, @Nullable Intent result) {
if (result == null || resultCode != Activity.RESULT_OK) {
return null;
}
return result.getData();
}
},
this::getFileFromUri);
public void launchFileFinder() {
Intent pickerIntent = new Intent(ACTION_OPEN_DOCUMENT);
pickerIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickerIntent.setType(" your mime type ");
pickerIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
launchFilePicker.launch(pickerIntent);
}
public void getFileFromUri(Uri result) {
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
InputStream stream = null;
try {
stream = AppMainActivity.this.getContentResolver().openInputStream(result);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (stream != null) {
try {
FileInputStream stream = new FileInputStream(importFile);
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
}
}
}