我有一个Web服务,根据图像ID提供一个字节数组。我想将这些字节数组转换为文件并存储在Android上,就像用户想要保存文件对话框中的文件格式完全相同。
我有一个Web服务,根据图像ID提供一个字节数组。我想将这些字节数组转换为文件并存储在Android上,就像用户想要保存文件对话框中的文件格式完全相同。
由于这是谷歌搜索该主题的最高结果,并且在我的研究过程中让我感到非常困惑,因此我认为我应该添加一个更新到这个问题。 自Android 19以来,已经有了内置的保存对话框。你甚至不需要任何权限(甚至不需要WRITE_EXTERNAL_STORAGE)。 它的工作方式非常简单:
//send an ACTION_CREATE_DOCUMENT intent to the system. It will open a dialog where the user can choose a location and a filename
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("YOUR FILETYPE"); //not needed, but maybe usefull
intent.putExtra(Intent.EXTRA_TITLE, "YOUR FILENAME"); //not needed, but maybe usefull
startActivityForResult(intent, SOME_INTEGER);
...
//after the user has selected a location you get an uri where you can write your data to:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == SOME_INTEGER && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
//just as an example, I am writing a String to the Uri I received from the user:
try {
OutputStream output = getContext().getContentResolver().openOutputStream(uri);
output.write(SOME_CONTENT.getBytes());
output.flush();
output.close();
}
catch(IOException e) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
}
}
更多内容请参见:https://developer.android.com/guide/topics/providers/document-provider
Android SDK没有提供自己的文件对话框,因此您需要构建自己的对话框。
Source:https://developer.android.com/training/data-storage/shared/documents-files#create-file
// Request code for creating a PDF document.
private final int SAVE_DOCUMENT_REQUEST_CODE = 0x445;
private File targetFile;
private void createFile() {
Uri reportFileUri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", targetFile);
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_TITLE, targetFile.getName());
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when your app creates the document.
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
startActivityForResult(intent, SAVE_DOCUMENT_REQUEST_CODE );
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SAVE_DOCUMENT_REQUEST_CODE && resultCode == RESULT_OK){
Uri uri = data.getData();
saveFile(uri);
}
}
private void saveFile(Uri uri) {
try {
OutputStream output = getContentResolver().openOutputStream(uri);
FileInputStream fileInputStream = new FileInputStream(targetFile);
byte[] bytes = new byte[(int) targetFile.length()];
fileInputStream.read(bytes, 0, bytes.length);
output.write(bytes);
output.flush();
output.close();
Log.i(TAG, "done");
} catch (IOException e) {
Log.e(TAG, "onActivityResult: ", e);
}
}
http://android-er.blogspot.com/2010/07/save-file-to-sd-card.html
http://www.blackmoonit.com/android/filebrowser/intents#intent.pick_file.new
@JodliDev已经提供了被接受的答案,但是startActivityForResult现在已经过时了,所以我想在这里提供我的解决方案,使用registerForActivityResult(ActivityResultContracts.CreateDocument())
首先注册一个ActivityResultLauncher,在其中定义结果应该发生什么。我们将得到uri返回,可以用于我们的OutpuStream。但一定要在开始时初始化它,否则你会得到:
片段必须在创建之前(即初始化、onAttach()或onCreate())调用registerForActivityResult()。
private var ics: String? = null
private val getFileUriForSavingICS = registerForActivityResult(ActivityResultContracts.CreateDocument()) { uri ->
if(ics.isNullOrEmpty())
return@registerForActivityResult
try {
val output: OutputStream? =
context?.contentResolver?.openOutputStream(uri)
output?.write(ics?.toByteArray())
output?.flush()
output?.close()
} catch (e: IOException) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show()
}
}
然后在需要的地方使用 .launch(...) 调用您的 ActivityResultLauncher。
getFileUriForSavingICS.launch("filename.txt")
就是这样 ;-) 您还可以更详细地了解ActivityResultContracts.CreateDocument()。此方法提供文档保存对话框,但其中还有其他有用的功能(例如启动相机意图)。请查看以下链接: https://developer.android.com/reference/androidx/activity/result/contract/ActivityResultContracts 以获取可能的ActivityResultContracts
或者请参阅https://developer.android.com/training/basics/intents/result以获取更多培训材料和有关如何创建自定义合同的信息!