Last active
August 29, 2015 14:06
-
-
Save ixiyang/cf292aceca9f9ff7f8e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CameraPictureUtil { | |
private static final String TAG = "CameraPictureUtil"; | |
public static final int RESULTCODE_IMAGE_LOCATION = 100, RESULT_FILE_LOCATION = 102, | |
RESULTCODE_IMAGE_CAMERA = 101; | |
// 获取相机拍摄图片 | |
public static String cameraImage(Activity activity) { | |
if (!LocalFileUtil.checkSdCardMount(activity)) { | |
return null; | |
} | |
String imagePath = null; | |
// 启动相机 | |
try { | |
String picName = TimeHelper.getYearToSeconds(System.currentTimeMillis()) + ".jpg"; | |
File file = new File(LocalFileUtil.getCamerapath(activity), picName); | |
file.createNewFile(); | |
if (file.exists()) { | |
Uri uri = Uri.fromFile(file); | |
imagePath = file.getAbsolutePath(); | |
Loger.info(TAG, "生成的图片途径是:" + imagePath); | |
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); | |
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); | |
activity.startActivityForResult(intent, RESULTCODE_IMAGE_CAMERA); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
DialogUtil.makeToast(activity, R.string.sd_createiamge_failed, 0); | |
imagePath = null; | |
} finally { | |
} | |
return imagePath; | |
} | |
// 获取相机拍摄图片 | |
public static String cameraImage(final Activity activity, String name) { | |
if (!LocalFileUtil.checkSdCardMount(activity)) { | |
return null; | |
} | |
String imagePath = null; | |
try { | |
File file = new File(LocalFileUtil.getCamerapath(activity), name); | |
file.createNewFile(); | |
if (file.exists()) { | |
Uri uri = Uri.fromFile(file); | |
imagePath = file.getAbsolutePath(); | |
Loger.info(TAG, "生成的图片途径是:" + imagePath); | |
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); | |
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); | |
activity.startActivityForResult(intent, RESULTCODE_IMAGE_CAMERA); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
DialogUtil.makeToast(activity, R.string.sd_createiamge_failed, 0); | |
imagePath = null; | |
} finally { | |
} | |
return imagePath; | |
} | |
/** | |
* 使用从相机拍摄的图片生成图片 | |
*/ | |
public static Bitmap decodeImageFromCamera(View view, String imagePath) { | |
int reqHeight = view.getHeight(); | |
int reqWidth = reqHeight;// ll_buttonbar.getWidth() / 6; | |
return BitmapUtil.decodeSampledBitmapFromPath(imagePath, reqWidth, reqHeight); | |
} | |
/** | |
* 从相册获取照片 | |
*/ | |
public static void locationImage(Activity activity) { | |
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; | |
Intent i = new Intent(Intent.ACTION_PICK, uri); | |
activity.startActivityForResult(i, RESULTCODE_IMAGE_LOCATION); | |
} | |
public static void locationFile(Activity activity) { | |
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); | |
// The MIME data type filter | |
intent.setType("*/*"); | |
// Only return URIs that can be opened with ContentResolver | |
intent.addCategory(Intent.CATEGORY_OPENABLE); | |
Intent c = Intent.createChooser(intent, activity.getString(R.string.pick_file)); | |
try { | |
activity.startActivityForResult(c, RESULT_FILE_LOCATION); | |
} catch (Exception e) { | |
} | |
} | |
/** | |
* 使用从相册选择的路径生成图片 | |
*/ | |
public static String getImageFromGallery(Activity activity, Intent data) { | |
Uri selectedImage = data.getData(); | |
String[] filePathColumn = { MediaStore.Images.Media.DATA }; | |
ContentResolver contentResolver = activity.getContentResolver(); | |
Cursor cursor = contentResolver.query(selectedImage, filePathColumn, null, null, null); | |
cursor.moveToFirst(); | |
int columnIndex = cursor.getColumnIndex(filePathColumn[0]); | |
String imagePath = cursor.getString(columnIndex); | |
cursor.close(); | |
return imagePath; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final String TAG = "QM_LocalFileUtil"; | |
private static final String ROOTPATH = "qimingcx"; | |
public static final File mSystemDowloadPath = new File( | |
Environment.getExternalStorageDirectory(), | |
Environment.DIRECTORY_DOWNLOADS); | |
private static LocalFileUtil mInstance; | |
private static File mRootPathFile = null; | |
private static File mTempPath = null; | |
private static File mSavePath = null; | |
private static final boolean DEBUG = false; // Set to true to enable logging | |
public static final String MIME_TYPE_AUDIO = "audio/*"; | |
public static final String MIME_TYPE_TEXT = "text/*"; | |
public static final String MIME_TYPE_IMAGE = "image/*"; | |
public static final String MIME_TYPE_VIDEO = "video/*"; | |
public static final String MIME_TYPE_APP = "application/*"; | |
public static final String HIDDEN_PREFIX = "."; | |
public static LocalFileUtil getInstance(Context context) { | |
if (mInstance == null) { | |
mInstance = new LocalFileUtil(); | |
} | |
mRootPathFile = new File( | |
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), | |
ROOTPATH); | |
mTempPath = new File(mRootPathFile, "temp"); | |
mSavePath = new File(mRootPathFile, "save"); | |
return mInstance; | |
} | |
private LocalFileUtil() { | |
} | |
public static String getSavePath(){ | |
if (mSavePath!=null) { | |
return mSavePath.getAbsolutePath(); | |
}else { | |
return ""; | |
} | |
} | |
public static void makeDirFile(String path) { | |
File file = new File(path); | |
if (!file.exists()) { | |
file.mkdirs(); | |
} | |
} | |
/** | |
* 下载文件的文件夹 | |
* | |
* @param context | |
* @param fileName | |
* @return | |
*/ | |
public static String getDownloadFilePath(Context context, String fileName) { | |
File file = new File( | |
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), | |
ROOTPATH); | |
if (!file.exists()) { | |
System.err.println("file not exists"); | |
file.mkdir(); | |
} | |
File rootFile = new File(file, "file"); | |
if (!rootFile.exists()) { | |
rootFile.mkdir(); | |
} | |
File lastFile = new File(rootFile, fileName); | |
return lastFile.getPath(); | |
} | |
/** | |
* 聊天的文件夹 | |
* | |
* @param context | |
* @param fileName | |
* @return | |
*/ | |
public static File getChatPath(Context context) { | |
File file = new File( | |
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), | |
ROOTPATH); | |
if (!file.exists()) { | |
file.mkdir(); | |
} | |
File rootFile = new File(file, "chat"); | |
if (!rootFile.exists()) { | |
rootFile.mkdir(); | |
} | |
return rootFile; | |
} | |
public static File getCamerapath(Context context) { | |
File file = new File( | |
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), | |
ROOTPATH); | |
if (!file.exists()) { | |
file.mkdir(); | |
} | |
File rootFile = new File(file, "camera"); | |
if (!rootFile.exists()) { | |
rootFile.mkdir(); | |
} | |
return rootFile; | |
} | |
/** | |
* 检查是否存在sd卡,不会对结果做提示 | |
*/ | |
public static boolean sdIsReady() { | |
return Environment.getExternalStorageState().equals( | |
Environment.MEDIA_MOUNTED); | |
} | |
/** | |
* 检查是否存在sd卡,并提供提示 | |
*/ | |
public static boolean checkSdCardMount(Context context) { | |
boolean isok = Environment.getExternalStorageState().equals( | |
Environment.MEDIA_MOUNTED); | |
if (!isok) { | |
DialogUtil.makeToast(context, R.string.sd_nonecard, 0); | |
} | |
return isok; | |
} | |
/** | |
* 检查sd卡空间是否剩余空间不足 | |
*/ | |
public static boolean shortSdCard() { | |
return false; | |
} | |
/* ******************* 文件保存方法 ********************** */ | |
/** | |
* 下载文件到path指定的目录,参数urlStr为下载链接,fileName为文件名 | |
*/ | |
private int downFile(String urlStr, File path, String fileName) { | |
int status = -1; | |
if (!sdIsReady()) { | |
status = -1; | |
} | |
if (!path.exists()) { | |
path.mkdirs(); | |
} | |
File realfile = new File(path, fileName); | |
// 文件已存在则直接返回 | |
if (realfile.exists()) { | |
status = 1; | |
// sd卡空间不足 | |
} else if (shortSdCard()) { | |
status = -2; | |
} else { | |
status = downFileFrom(urlStr, path, fileName); | |
} | |
return status; | |
} | |
private int downFileFrom(String urlStr, File path, String fileName) { | |
int status; | |
InputStream in = null; | |
BufferedOutputStream bos = null; | |
try { | |
in = getInputStreamFromNet(urlStr); | |
bos = writeOutputSreamFromInputStream(path, fileName, in); | |
status = 0; | |
} catch (ClientProtocolException e) { | |
e.printStackTrace(); | |
status = -1; | |
Loger.info(TAG, "exception---->" + e.getMessage()); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
status = -1; | |
Loger.info(TAG, "exception---->" + e.getMessage()); | |
} finally { | |
if (in != null) | |
try { | |
in.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
if (bos != null) | |
try { | |
bos.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return status; | |
} | |
private BufferedOutputStream writeOutputSreamFromInputStream(File path, | |
String fileName, InputStream in) throws IOException { | |
String tmpName = fileName + ".tmp"; | |
File file = new File(path, tmpName); | |
file.createNewFile(); | |
BufferedOutputStream bos; | |
FileOutputStream out = new FileOutputStream(file); | |
bos = new BufferedOutputStream(out); | |
byte[] bytes = new byte[8 * 1024]; | |
int length = 0; | |
int size = 0; | |
while ((length = in.read(bytes)) != -1) { | |
bos.write(bytes, 0, length); | |
bos.flush(); | |
size = size + length; | |
Loger.info(TAG, "下载了大小:" + size); | |
} | |
File newPath = new File(file.getParentFile(), fileName); | |
file.renameTo(newPath); | |
return bos; | |
} | |
private InputStream getInputStreamFromNet(String urlStr) throws IOException { | |
HttpClient client = SSLSocketFactoryEx.getNewHttpClient(); | |
Loger.info(TAG, "使用的下载链接是:" + urlStr); | |
HttpGet get = new HttpGet(urlStr); | |
HttpResponse response = client.execute(get); | |
HttpEntity httpEntity = response.getEntity(); | |
long filesize = httpEntity.getContentLength(); | |
Loger.info(TAG, "文件大小是:" + filesize); | |
return httpEntity.getContent(); | |
} | |
/** | |
* 下载文件到系统的Download目录,参数urlStr为下载链接,fileName为文件名 | |
*/ | |
public int downFileToDownloadPath(String urlStr, String fileName) { | |
return downFile(urlStr, mSystemDowloadPath, fileName); | |
} | |
/** | |
* 由于多线程的使用,首先在图片类型所在文件夹查找文件, 文件存在则不再写入,文件不存在则将文件下载到临时目录, 下载完成后移入图片类型对应的文件夹 | |
*/ | |
public boolean putBitmap2SDCard(Bitmap bitmap, String imageurl, | |
String filetype) { | |
// 文件可写性判断 | |
if (!sdIsReady()) { | |
return false; | |
} | |
File savePath = getBitmapFile(imageurl, mSavePath); | |
if (savePath.exists()) { | |
return true; | |
} | |
// 写入文件 | |
File tempFile = getBitmapFile(imageurl, mTempPath); | |
FileOutputStream out = null; | |
try { | |
tempFile.createNewFile(); | |
out = new FileOutputStream(tempFile); | |
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out); | |
tempFile.renameTo(savePath); | |
return true; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return false; | |
} finally { | |
try { | |
if (out != null) | |
out.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
/** | |
* 获取图片所在路径 | |
*/ | |
private File getBitmapFile(String imageurl, File file) { | |
String filename = MD5Util.getMD5(imageurl); | |
if (!file.exists()) { | |
file.mkdirs(); | |
Loger.info(TAG, file + ",文件夹不存在,创建建文件夹"); | |
} else { | |
Loger.info(TAG, file + ",文件夹已存在"); | |
} | |
File destFile = new File(file, filename + ".png"); | |
return destFile; | |
} | |
/** | |
* 递归删除文件和文件夹 | |
* | |
* @param file | |
* 要删除的根目录 | |
*/ | |
public static void deleteFile(File file) { | |
if (!file.exists()) { | |
return; | |
} | |
if (file.isFile()) { | |
file.delete(); | |
return; | |
} | |
if (file.isDirectory()) { | |
File[] childFile = file.listFiles(); | |
if (childFile == null || childFile.length == 0) { | |
file.delete(); | |
return; | |
} | |
for (File f : childFile) { | |
deleteFile(f); | |
} | |
} | |
file.delete(); | |
} | |
/** | |
* 得到文件流 | |
* | |
* @param file | |
* @return | |
*/ | |
public static InputStream getStreamFromFile(File file) { | |
byte[] b = new byte[1024]; | |
try { | |
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | |
InputStream is = new FileInputStream(file); | |
while ((is.read(b)) != -1) { | |
baos.write(b, 0, b.length); | |
} | |
is.close(); | |
return new ByteArrayInputStream(baos.toByteArray()); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
return null; | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
// 定义用于检查要打开的文件的后缀是否在遍历后缀数组中 | |
public static boolean checkEndsWithInStringArray(String checkItsEnd, | |
String[] fileEndings) { | |
for (String aEnd : fileEndings) { | |
if (checkItsEnd.endsWith(aEnd)) | |
return true; | |
} | |
return false; | |
} | |
// android获取一个用于打开HTML文件的intent | |
public static Intent getHtmlFileIntent(File file) { | |
Uri uri = Uri.parse(file.toString()).buildUpon() | |
.encodedAuthority("com.android.htmlfileprovider") | |
.scheme("content").encodedPath(file.toString()).build(); | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.setDataAndType(uri, "text/html"); | |
return intent; | |
} | |
// android获取一个用于打开图片文件的intent | |
public static Intent getImageFileIntent(File file) { | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.addCategory("android.intent.category.DEFAULT"); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
Uri uri = Uri.fromFile(file); | |
intent.setDataAndType(uri, "image/*"); | |
return intent; | |
} | |
// android获取一个用于打开PDF文件的intent | |
public static Intent getPdfFileIntent(File file) { | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.addCategory("android.intent.category.DEFAULT"); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
Uri uri = Uri.fromFile(file); | |
intent.setDataAndType(uri, "application/pdf"); | |
return intent; | |
} | |
// android获取一个用于打开文本文件的intent | |
public static Intent getTextFileIntent(File file) { | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.addCategory("android.intent.category.DEFAULT"); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
Uri uri = Uri.fromFile(file); | |
intent.setDataAndType(uri, "text/plain"); | |
return intent; | |
} | |
// android获取一个用于打开音频文件的intent | |
public static Intent getAudioFileIntent(File file) { | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); | |
intent.putExtra("oneshot", 0); | |
intent.putExtra("configchange", 0); | |
Uri uri = Uri.fromFile(file); | |
intent.setDataAndType(uri, "audio/*"); | |
return intent; | |
} | |
// android获取一个用于打开视频文件的intent | |
public static Intent getVideoFileIntent(File file) { | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); | |
intent.putExtra("oneshot", 0); | |
intent.putExtra("configchange", 0); | |
Uri uri = Uri.fromFile(file); | |
intent.setDataAndType(uri, "video/*"); | |
return intent; | |
} | |
// android获取一个用于打开CHM文件的intent | |
public static Intent getChmFileIntent(File file) { | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.addCategory("android.intent.category.DEFAULT"); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
Uri uri = Uri.fromFile(file); | |
intent.setDataAndType(uri, "application/x-chm"); | |
return intent; | |
} | |
// android获取一个用于打开Word文件的intent | |
public static Intent getWordFileIntent(File file) { | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.addCategory("android.intent.category.DEFAULT"); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
Uri uri = Uri.fromFile(file); | |
intent.setDataAndType(uri, "application/msword"); | |
return intent; | |
} | |
// android获取一个用于打开Excel文件的intent | |
public static Intent getExcelFileIntent(File file) { | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.addCategory("android.intent.category.DEFAULT"); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
Uri uri = Uri.fromFile(file); | |
intent.setDataAndType(uri, "application/vnd.ms-excel"); | |
return intent; | |
} | |
// android获取一个用于打开PPT文件的intent | |
public static Intent getPPTFileIntent(File file) { | |
Intent intent = new Intent("android.intent.action.VIEW"); | |
intent.addCategory("android.intent.category.DEFAULT"); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
Uri uri = Uri.fromFile(file); | |
intent.setDataAndType(uri, "application/vnd.ms-powerpoint"); | |
return intent; | |
} | |
// android获取一个用于打开apk文件的intent | |
public static Intent getApkFileIntent(File file) { | |
Intent intent = new Intent(); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
intent.setAction(android.content.Intent.ACTION_VIEW); | |
intent.setDataAndType(Uri.fromFile(file), | |
"application/vnd.android.package-archive"); | |
return intent; | |
} | |
/** | |
* Gets the extension of a file name, like ".png" or ".jpg". | |
* | |
* @param uri | |
* @return Extension including the dot("."); "" if there is no extension; | |
* null if uri was null. | |
*/ | |
public static String getExtension(String uri) { | |
if (uri == null) { | |
return null; | |
} | |
int dot = uri.lastIndexOf("."); | |
if (dot >= 0) { | |
return uri.substring(dot); | |
} else { | |
// No extension. | |
return ""; | |
} | |
} | |
/** | |
* @return Whether the URI is a local one. | |
*/ | |
public static boolean isLocal(String url) { | |
if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) { | |
return true; | |
} | |
return false; | |
} | |
/** | |
* @return True if Uri is a MediaStore Uri. | |
* @author paulburke | |
*/ | |
public static boolean isMediaUri(Uri uri) { | |
return "media".equalsIgnoreCase(uri.getAuthority()); | |
} | |
/** | |
* Convert File into Uri. | |
* | |
* @param file | |
* @return uri | |
*/ | |
public static Uri getUri(File file) { | |
if (file != null) { | |
return Uri.fromFile(file); | |
} | |
return null; | |
} | |
/** | |
* Returns the path only (without file name). | |
* | |
* @param file | |
* @return | |
*/ | |
public static File getPathWithoutFilename(File file) { | |
if (file != null) { | |
if (file.isDirectory()) { | |
// no file to be split off. Return everything | |
return file; | |
} else { | |
String filename = file.getName(); | |
String filepath = file.getAbsolutePath(); | |
// Construct path without file name. | |
String pathwithoutname = filepath.substring(0, | |
filepath.length() - filename.length()); | |
if (pathwithoutname.endsWith("/")) { | |
pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1); | |
} | |
return new File(pathwithoutname); | |
} | |
} | |
return null; | |
} | |
/** | |
* @return The MIME type for the given file. | |
*/ | |
public static String getMimeType(File file) { | |
String extension = getExtension(file.getName()); | |
if (extension.length() > 0) | |
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1)); | |
return "application/octet-stream"; | |
} | |
/** | |
* @return The MIME type for the give Uri. | |
*/ | |
public static String getMimeType(Context context, Uri uri) { | |
File file = new File(getPath(context, uri)); | |
return getMimeType(file); | |
} | |
/** | |
* @param uri The Uri to check. | |
* @return Whether the Uri authority is {@link LocalStorageProvider}. | |
* @author paulburke | |
*/ | |
public static boolean isLocalStorageDocument(Uri uri) { | |
return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority()); | |
} | |
/** | |
* @param uri The Uri to check. | |
* @return Whether the Uri authority is ExternalStorageProvider. | |
* @author paulburke | |
*/ | |
public static boolean isExternalStorageDocument(Uri uri) { | |
return "com.android.externalstorage.documents".equals(uri.getAuthority()); | |
} | |
/** | |
* @param uri The Uri to check. | |
* @return Whether the Uri authority is DownloadsProvider. | |
* @author paulburke | |
*/ | |
public static boolean isDownloadsDocument(Uri uri) { | |
return "com.android.providers.downloads.documents".equals(uri.getAuthority()); | |
} | |
/** | |
* @param uri The Uri to check. | |
* @return Whether the Uri authority is MediaProvider. | |
* @author paulburke | |
*/ | |
public static boolean isMediaDocument(Uri uri) { | |
return "com.android.providers.media.documents".equals(uri.getAuthority()); | |
} | |
/** | |
* @param uri The Uri to check. | |
* @return Whether the Uri authority is Google Photos. | |
*/ | |
public static boolean isGooglePhotosUri(Uri uri) { | |
return "com.google.android.apps.photos.content".equals(uri.getAuthority()); | |
} | |
/** | |
* Get the value of the data column for this Uri. This is useful for | |
* MediaStore Uris, and other file-based ContentProviders. | |
* | |
* @param context The context. | |
* @param uri The Uri to query. | |
* @param selection (Optional) Filter used in the query. | |
* @param selectionArgs (Optional) Selection arguments used in the query. | |
* @return The value of the _data column, which is typically a file path. | |
* @author paulburke | |
*/ | |
public static String getDataColumn(Context context, Uri uri, String selection, | |
String[] selectionArgs) { | |
Cursor cursor = null; | |
final String column = "_data"; | |
final String[] projection = { | |
column | |
}; | |
try { | |
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, | |
null); | |
if (cursor != null && cursor.moveToFirst()) { | |
if (DEBUG) | |
DatabaseUtils.dumpCursor(cursor); | |
final int column_index = cursor.getColumnIndexOrThrow(column); | |
return cursor.getString(column_index); | |
} | |
} finally { | |
if (cursor != null) | |
cursor.close(); | |
} | |
return null; | |
} | |
/** | |
* Get a file path from a Uri. This will get the the path for Storage Access | |
* Framework Documents, as well as the _data field for the MediaStore and | |
* other file-based ContentProviders.<br> | |
* <br> | |
* Callers should check whether the path is local before assuming it | |
* represents a local file. | |
* | |
* @param context The context. | |
* @param uri The Uri to query. | |
* @see #isLocal(String) | |
* @see #getFile(Context, Uri) | |
* @author paulburke | |
*/ | |
@SuppressLint("NewApi") | |
public static String getPath(final Context context, final Uri uri) { | |
if (DEBUG) | |
Loger.error(TAG + " File -", | |
"Authority: " + uri.getAuthority() + | |
", Fragment: " + uri.getFragment() + | |
", Port: " + uri.getPort() + | |
", Query: " + uri.getQuery() + | |
", Scheme: " + uri.getScheme() + | |
", Host: " + uri.getHost() + | |
", Segments: " + uri.getPathSegments().toString() | |
); | |
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; | |
// DocumentProvider | |
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { | |
// LocalStorageProvider | |
if (isLocalStorageDocument(uri)) { | |
// The path is the id | |
return DocumentsContract.getDocumentId(uri); | |
} | |
// ExternalStorageProvider | |
else if (isExternalStorageDocument(uri)) { | |
final String docId = DocumentsContract.getDocumentId(uri); | |
final String[] split = docId.split(":"); | |
final String type = split[0]; | |
if ("primary".equalsIgnoreCase(type)) { | |
return Environment.getExternalStorageDirectory() + "/" + split[1]; | |
} | |
// TODO handle non-primary volumes | |
} | |
// DownloadsProvider | |
else if (isDownloadsDocument(uri)) { | |
final String id = DocumentsContract.getDocumentId(uri); | |
final Uri contentUri = ContentUris.withAppendedId( | |
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); | |
return getDataColumn(context, contentUri, null, null); | |
} | |
// MediaProvider | |
else if (isMediaDocument(uri)) { | |
final String docId = DocumentsContract.getDocumentId(uri); | |
final String[] split = docId.split(":"); | |
final String type = split[0]; | |
Uri contentUri = null; | |
if ("image".equals(type)) { | |
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; | |
} else if ("video".equals(type)) { | |
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; | |
} else if ("audio".equals(type)) { | |
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; | |
} | |
final String selection = "_id=?"; | |
final String[] selectionArgs = new String[] { | |
split[1] | |
}; | |
return getDataColumn(context, contentUri, selection, selectionArgs); | |
} | |
} | |
// MediaStore (and general) | |
else if ("content".equalsIgnoreCase(uri.getScheme())) { | |
// Return the remote address | |
if (isGooglePhotosUri(uri)) | |
return uri.getLastPathSegment(); | |
return getDataColumn(context, uri, null, null); | |
} | |
// File | |
else if ("file".equalsIgnoreCase(uri.getScheme())) { | |
return uri.getPath(); | |
} | |
return null; | |
} | |
/** | |
* Convert Uri into File, if possible. | |
* | |
* @return file A local file that the Uri was pointing to, or null if the | |
* Uri is unsupported or pointed to a remote resource. | |
* @see #getPath(Context, Uri) | |
* @author paulburke | |
*/ | |
public static File getFile(Context context, Uri uri) { | |
if (uri != null) { | |
String path = getPath(context, uri); | |
if (path != null && isLocal(path)) { | |
return new File(path); | |
} | |
} | |
return null; | |
} | |
/** | |
* Get the file size in a human-readable string. | |
* | |
* @param size | |
* @return | |
* @author paulburke | |
*/ | |
public static String getReadableFileSize(int size) { | |
final int BYTES_IN_KILOBYTES = 1024; | |
final DecimalFormat dec = new DecimalFormat("###.#"); | |
final String KILOBYTES = " KB"; | |
final String MEGABYTES = " MB"; | |
final String GIGABYTES = " GB"; | |
float fileSize = 0; | |
String suffix = KILOBYTES; | |
if (size > BYTES_IN_KILOBYTES) { | |
fileSize = size / BYTES_IN_KILOBYTES; | |
if (fileSize > BYTES_IN_KILOBYTES) { | |
fileSize = fileSize / BYTES_IN_KILOBYTES; | |
if (fileSize > BYTES_IN_KILOBYTES) { | |
fileSize = fileSize / BYTES_IN_KILOBYTES; | |
suffix = GIGABYTES; | |
} else { | |
suffix = MEGABYTES; | |
} | |
} | |
} | |
return String.valueOf(dec.format(fileSize) + suffix); | |
} | |
/** | |
* Attempt to retrieve the thumbnail of given File from the MediaStore. This | |
* should not be called on the UI thread. | |
* | |
* @param context | |
* @param file | |
* @return | |
* @author paulburke | |
*/ | |
public static Bitmap getThumbnail(Context context, File file) { | |
return getThumbnail(context, getUri(file), getMimeType(file)); | |
} | |
/** | |
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This | |
* should not be called on the UI thread. | |
* | |
* @param context | |
* @param uri | |
* @return | |
* @author paulburke | |
*/ | |
public static Bitmap getThumbnail(Context context, Uri uri) { | |
return getThumbnail(context, uri, getMimeType(context, uri)); | |
} | |
/** | |
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This | |
* should not be called on the UI thread. | |
* | |
* @param context | |
* @param uri | |
* @param mimeType | |
* @return | |
* @author paulburke | |
*/ | |
public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) { | |
if (DEBUG) | |
Loger.error(TAG, "Attempting to get thumbnail"); | |
if (!isMediaUri(uri)) { | |
Loger.error(TAG, "You can only retrieve thumbnails for images and videos."); | |
return null; | |
} | |
Bitmap bm = null; | |
if (uri != null) { | |
final ContentResolver resolver = context.getContentResolver(); | |
Cursor cursor = null; | |
try { | |
cursor = resolver.query(uri, null, null, null, null); | |
if (cursor.moveToFirst()) { | |
final int id = cursor.getInt(0); | |
if (DEBUG) | |
Loger.error(TAG, "Got thumb ID: " + id); | |
if (mimeType.contains("video")) { | |
bm = MediaStore.Video.Thumbnails.getThumbnail( | |
resolver, | |
id, | |
MediaStore.Video.Thumbnails.MINI_KIND, | |
null); | |
} | |
else if (mimeType.contains(MIME_TYPE_IMAGE)) { | |
bm = MediaStore.Images.Thumbnails.getThumbnail( | |
resolver, | |
id, | |
MediaStore.Images.Thumbnails.MINI_KIND, | |
null); | |
} | |
} | |
} catch (Exception e) { | |
if (DEBUG) | |
Loger.error(TAG, "getThumbnail"); | |
} finally { | |
if (cursor != null) | |
cursor.close(); | |
} | |
} | |
return bm; | |
} | |
/** | |
* File and folder comparator. TODO Expose sorting option method | |
* | |
* @author paulburke | |
*/ | |
public static Comparator<File> sComparator = new Comparator<File>() { | |
@Override | |
public int compare(File f1, File f2) { | |
// Sort alphabetically by lower case, which is much cleaner | |
return f1.getName().toLowerCase().compareTo( | |
f2.getName().toLowerCase()); | |
} | |
}; | |
/** | |
* File (not directories) filter. | |
* | |
* @author paulburke | |
*/ | |
public static FileFilter sFileFilter = new FileFilter() { | |
@Override | |
public boolean accept(File file) { | |
final String fileName = file.getName(); | |
// Return files only (not directories) and skip hidden files | |
return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX); | |
} | |
}; | |
/** | |
* Folder (directories) filter. | |
* | |
* @author paulburke | |
*/ | |
public static FileFilter sDirFilter = new FileFilter() { | |
@Override | |
public boolean accept(File file) { | |
final String fileName = file.getName(); | |
// Return directories only and skip hidden directories | |
return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX); | |
} | |
}; | |
/** | |
* Get the Intent for selecting content to be used in an Intent Chooser. | |
* | |
* @return The intent for opening a file with Intent.createChooser() | |
* @author paulburke | |
*/ | |
public static Intent createGetContentIntent() { | |
// Implicitly allow the user to select a particular kind of data | |
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); | |
// The MIME data type filter | |
intent.setType("*/*"); | |
// Only return URIs that can be opened with ContentResolver | |
intent.addCategory(Intent.CATEGORY_OPENABLE); | |
return intent; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment