如何在Android中打开文件保存对话框?

Sus*_*gar 2 android android-widget android-layout

我有一个Web服务,根据图像id,给我一个byte []数组。我想将这些byte []转换为文件,然后将文件存储在android上,用户想要在其中保存具有相同格式的文件的对话框。

Jod*_*Dev 5

由于这是当您搜索该主题时在Google中排名第一的结果,当我对其进行研究时,它使我感到非常困惑,因此我想我对此问题进行了更新。自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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

此处更多内容:https//developer.android.com/guide/topics/providers/document-provider


him*_*shu 3

您无法创建保存文件对话框,但您可以借助以下链接将文件从您的应用程序保存到 Android SD 卡

http://android-er.blogspot.com/2010/07/save-file-to-sd-card.html

http://www.blackmoonit.com/android/filebrowser/intents#intent.pick_file.new

  • 在您的应用程序中创建编辑文本或创建一个包含编辑文本的对话框。在编辑文本中写入您要保存文件的路径。使用 getText() 获取路径并将对象放入 File file = new File(extStorageDirectory) ,“呃.PNG”);在 er.PNG.Than 的位置,最后一段代码将是 File file = new File(extStorageDirectory, "OBJECT"); (2认同)