Bea*_*ear 108 file-io android file-upload filechooser android-afilechooser
我想制作一个文件上传器.因此,我需要一个文件选择器,但我不想自己写这个.我找到了OI文件管理器,我认为它适合我.但是我如何强制用户安装OI文件管理器?如果我不能,是否有更好的方法在我的应用程序中包含文件管理器?谢谢
Pau*_*rke 257
编辑(2012年1月2日):
我创建了一个小型开源Android库项目,简化了这个过程,同时还提供了一个内置的文件浏览器(如果用户没有一个存在).它使用起来非常简单,只需要几行代码.
你可以在GitHub找到它:aFileChooser.
原版的
如果您希望用户能够选择系统中的任何文件,则需要包含您自己的文件管理器,或建议用户下载文件管理器.我相信你能做的最好的事情就是找到这样的"可打开的"内容Intent.createChooser()
:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这样,你会听所选文件的Uri
在onActivityResult()
像这样:
@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);
}
Run Code Online (Sandbox Code Playgroud)
getPath()
我的方法FileUtils.java
是:
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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
203621 次 |
最近记录: |