[英]Android FilePicker dialog only working for some devices
我正在使用常规样板代码在Android上显示“文件选择器”对话框。 获取文件路径后,我将使用aQuery将该文件上传到服务器。 但是,该代码仅能在运行于Android 4.1.2的旧三星手机上运行,而不能在任何其他设备上运行。 我使用许多设备对其进行了测试,但仅在具有JellyBean的Samsung设备上有效。
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(minmeType);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
// if you want any file type, you can skip next line
sIntent.putExtra("CONTENT_TYPE", minmeType);
sIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent chooserIntent;
if (getPackageManager().resolveActivity(sIntent, 0) != null) {
// it is device with samsung file manager
chooserIntent = Intent.createChooser(sIntent, "Open file");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{intent});
} else {
chooserIntent = Intent.createChooser(intent, "Open file");
}
try {
startActivityForResult(chooserIntent, PICKFILE_REQUEST_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "No suitable File Manager was found.\nPlease download a File Manager and try again.", Toast.LENGTH_LONG).show();
}
onActivityResult代码为:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
fPath = data.getDataString();
File file = new File(fPath.substring(7));
params.put("file" + noFilesAttached, file);
noFilesAttached = noFilesAttached + 1;
path.setText(noFilesAttached + " files attached ");
upload.setText("Upload (" + noFilesAttached + ")");
upload.setVisibility(View.VISIBLE);
isUploaded = false;
}
super.onActivityResult(requestCode, resultCode, data);
}
我试图编辑fPath.substring(7),没有成功fpath,我不希望使用任何第三方库。
提前致谢。
尝试使用此库
该库可能会解决您的要求。
Data.getData()
返回uri
; 你需要一个文件路径; 尝试找到将uri
转换为文件路径的方法:可能:
public static String getRealFilePath( final Context context, final Uri uri ) {
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( ImageColumns.DATA );
if ( index > -1 ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.