参考: http://stackoverflow.com/questions/7856959/android-file-chooser EDIT's answer.
版权所有,转载注明。
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);//这里可能需要加个异常捕捉处理
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
如果你能墙,下面的链接可以看看:
原文如下:
android-file-chooser
Android file chooser
A simple file chooser to android applications.
Possible add filters extensions, ex:
ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".pdf");
extensions.add(".xls");
extensions.add(".xlsx");
intent.putStringArrayListExtra("filterFileExtension", extensions);
startActivityForResult(intent, FILE_CHOOSER);```
> Returns
```@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == FILE_CHOOSER) && (resultCode == -1)) {
String fileSelected = data.getStringExtra("fileSelected");
Toast.makeText(this, fileSelected, Toast.LENGTH_SHORT).show();
}
}```
![https://lh3.googleusercontent.com/-6RoRJPyHxTM/TtmTO4L2RfI/AAAAAAAAA70/EBzuRjv9Nf4/s720/fileChooser.png](https://lh3.googleusercontent.com/-6RoRJPyHxTM/TtmTO4L2RfI/AAAAAAAAA70/EBzuRjv9Nf4/s720/fileChooser.png)