如何使用原生的android文件 - 打开对话框?

时间:2016-04-11 19:45:08

标签: android fileopendialog

我已经看到这个对话框在某些应用程序中选择/打开android上的文件,在我看来它是本机的。但我找不到在自己的应用中使用它的方法。所附截图的语言是德语,但我确信有人会识别它。 Screenshot of the file-dialog

3 个答案:

答案 0 :(得分:42)

您可以将意图 ACTION_GET_CONTENT MIME类型 */*结合使用。

它将返回 onActivityResult()

中的URI
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent()
        .setType("*/*")
        .setAction(Intent.ACTION_GET_CONTENT);

        startActivityForResult(Intent.createChooser(intent, "Select a file"), 123);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 123 && resultCode == RESULT_OK) {
            Uri selectedfile = data.getData(); //The uri with the location of the file
        }
    }

Screenshot

答案 1 :(得分:5)

这似乎是the Storage Access Framework的系统用户界面。您可以使用ACTION_OPEN_DOCUMENT来允许用户打开现有文档,或使用ACTION_CREATE_DOCUMENT以允许用户创建新文档。

但是,这不是文件 UI。它是内容 UI。用户可以浏览非本地存储的内容 - 在屏幕截图中,用户可以浏览他们的Google云端硬盘和One Drive区域。而且,你得到的是a Uri pointing to content, not a file path

答案 2 :(得分:0)

Android developer documents and files documentations。 在 Kotlin 中,您可以launch file open dialog like that

/**
 * Starts bookmarks import workflow by showing file selection dialog.
 */
private fun showImportBookmarksDialog() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
    addCategory(Intent.CATEGORY_OPENABLE)
    type = "*/*" // That's needed for some reason, crashes otherwise
      putExtra(
        // List all file types you want the user to be able to select
        Intent.EXTRA_MIME_TYPES, arrayOf(
            "text/html", // .html
            "text/plain" // .txt
        )
    )
}
bookmarkImportFilePicker.launch(intent)
// See bookmarkImportFilePicker declaration below for result handler
}

// Assuming you have context access as a fragment or an activity
val bookmarkImportFilePicker = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        result: ActivityResult ->
    if (result.resultCode == Activity.RESULT_OK) {
        // Using content resolver to get an input stream from selected URI
        // See:  https://commonsware.com/blog/2016/03/15/how-consume-content-uri.html
        result.data?.data?.let{ uri ->
            context?.contentResolver?.openInputStream(uri).let { inputStream ->
                val mimeType = context?.contentResolver?.getType(uri)
                // TODO: do your stuff like check the MIME type and read from that input stream
        }
    }
}