我正在一台安装了Android 4.0.3系统的设备上进行开发。如何为我的应用程序打开一个文件浏览器呢?在Android SDK中是否有内置的文件浏览器?还是必须自己编写?
我不想让我的应用程序依赖于用户安装单独的文件浏览器应用。
我正在一台安装了Android 4.0.3系统的设备上进行开发。如何为我的应用程序打开一个文件浏览器呢?在Android SDK中是否有内置的文件浏览器?还是必须自己编写?
我不想让我的应用程序依赖于用户安装单独的文件浏览器应用。
要从文件浏览器中获取文件,请使用以下方法:
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("gagt/sdf");
try {
startActivityForResult(fileintent, PICKFILE_RESULT_CODE);
} catch (ActivityNotFoundException e) {
Log.e("tag", "No activity can handle picking a file. Showing alternatives.");
}
我不太确定gagt/sdf的作用是什么......但它似乎在我的应用程序中适用于任何文件。
然后添加这个方法:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Fix no activity available
if (data == null)
return;
switch (requestCode) {
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK) {
String FilePath = data.getData().getPath();
//FilePath is your file as a string
}
}
如果用户没有安装或预先安装他们的OEM没有提供文件管理器应用程序,那么您将不得不实现自己的文件管理器。你最好给他们一个选择。
public void performFileSearch() {
// ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
// browser.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
// Filter to only show results that can be "opened", such as a
// file (as opposed to a list of contacts or timezones)
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only images, using the image MIME data type.
// If one wanted to search for ogg vorbis files, the type would be "audio/ogg".
// To search for all documents available via installed storage providers,
// it would be "*/*".
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
这段代码来自以下文档:
https://developer.android.com/guide/topics/providers/document-provider.html
请参考该文档获取更多信息。
如果有人需要在更新的版本中使用它,它已经通过Google开发的存储访问框架进行了更新,该框架适用于SDK >= 4.4。请查看此Google网站以获取更多详情:
https://developer.android.com/guide/topics/providers/document-provider.html
没有一款文件管理应用程序可以在所有设备上安装。
您可能希望您的应用程序也能在 Android 3.x 或更低版本的设备上运行。
不过,您最好的选择是编写自己的文件管理器。这并不需要像听起来那么费力,因为网络上已经有很多相关代码了。