Search

Android - KitKat 以上版本從 URI 取得檔案實體路徑

2016-05-26 9:42 AM

有時使用檔案選擇器取得路徑時會發現路徑是奇怪的 content://downloads/public_downloads 字串

而這種路徑使用 context.getContentResolver().query(); 方法取得的路徑會是空的

其實是因為新版 Android 在路徑上是使用 uri 的方式表示的

有點像網址,好處是同一個 uri 可以指定到不同的實體路徑內

用以對應不同的開發商與使用者設定

壞處就是取得路徑的方法變得較麻煩(而且官方文件似乎找不到方法? WTF?)

而且很多類型的檔案取得路徑的方式也沒有統一

以下就是對應各版本(4.4 以上)取得路徑的 FileUtil 的原始碼

檔案瀏覽器的使用方式可以到 啟動檔案瀏覽器選擇檔案 教學查看

程式碼範例
  1. import android.content.ContentUris;
  2. import android.content.Context;
  3. import android.database.Cursor;
  4. import android.net.Uri;
  5. import android.os.Environment;
  6. import android.provider.DocumentsContract;
  7. import android.provider.MediaStore;
  8. import cmc.toolkit.FileKit;
  9. import com.ihad.ptt.model.exception.EmptyFilePathException;
  10. import com.ihad.ptt.model.exception.IllegalTrueTypeFontException;
  11.  
  12. import java.io.File;
  13. import java.io.FileNotFoundException;
  14.  
  15. public class FileUtils {
  16.  
  17. /**
  18. * 從 uri 取得檔案路徑 這將從 Storage Access Framework Documents 取得路徑
  19. * 也會使用從 _data 欄位取得 MediaStore 以及其他 file-based ContentProviders 的對應路徑
  20. *
  21. * @param context The context.
  22. * @param uri The Uri to query.
  23. * @author paulburke
  24. */
  25. public static String getPath(final Context context, final Uri uri) {
  26.  
  27. // DocumentProvider
  28. if ( DocumentsContract.isDocumentUri(context, uri) ) {
  29. // ExternalStorageProvider
  30. if (isExternalStorageDocument(uri)) {
  31. final String docId = DocumentsContract.getDocumentId(uri);
  32. final String[] split = docId.split(":");
  33. final String type = split[0];
  34.  
  35. if ("primary".equalsIgnoreCase(type)) {
  36. String path = Environment.getExternalStorageDirectory().getPath();
  37.  
  38. if (split.length > 1) {
  39. path += "/" + split[1];
  40. }
  41.  
  42. return path;
  43. }
  44. else {
  45. String path;
  46. if (Environment.isExternalStorageRemovable()) {
  47. path = System.getenv("EXTERNAL_STORAGE");
  48. } else {
  49. path = System.getenv("SECONDARY_STORAGE");
  50. if (path == null || path.length() == 0) {
  51. path = System.getenv("EXTERNAL_SDCARD_STORAGE");
  52. }
  53. }
  54.  
  55. if (split.length > 1) {
  56. path += "/" + split[1];
  57. }
  58.  
  59. return path;
  60. }
  61. }
  62. // DownloadsProvider
  63. else if (isDownloadsDocument(uri)) {
  64.  
  65. final String id = DocumentsContract.getDocumentId(uri);
  66. final Uri contentUri = ContentUris.withAppendedId(
  67. Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
  68.  
  69. return getDataColumn(context, contentUri, null, null);
  70. }
  71. // MediaProvider
  72. else if (isMediaDocument(uri)) {
  73. final String docId = DocumentsContract.getDocumentId(uri);
  74. final String[] split = docId.split(":");
  75. final String type = split[0];
  76.  
  77. Uri contentUri = null;
  78. if ("image".equals(type)) {
  79. contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  80. } else if ("video".equals(type)) {
  81. contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
  82. } else if ("audio".equals(type)) {
  83. contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  84. }
  85.  
  86. final String selection = "_id=?";
  87. final String[] selectionArgs = new String[] {
  88. split[1]
  89. };
  90.  
  91. return getDataColumn(context, contentUri, selection, selectionArgs);
  92. }
  93. }
  94. // MediaStore (and general)
  95. else if ("content".equalsIgnoreCase(uri.getScheme())) {
  96. // Return the remote address
  97. if (isGooglePhotosUri(uri)) return uri.getLastPathSegment();
  98.  
  99. return getDataColumn(context, uri, null, null);
  100. }
  101. // File
  102. else if ("file".equalsIgnoreCase(uri.getScheme())) {
  103. return uri.getPath();
  104. }
  105.  
  106. return null;
  107. }
  108.  
  109. /**
  110. * 從 data 欄位取得 uri 對應的實體路徑
  111. * 主要用以取得 MediaStore Uris 以及其他 file-based ContentProviders 的對應路徑
  112. *
  113. * @param context The context.
  114. * @param uri The Uri to query.
  115. * @param selection (Optional) Filter used in the query.
  116. * @param selectionArgs (Optional) Selection arguments used in the query.
  117. * @return The value of the _data column, which is typically a file path.
  118. * @author paulburke
  119. */
  120. public static String getDataColumn(Context context, Uri uri, String selection,
  121. String[] selectionArgs) {
  122.  
  123. Cursor cursor = null;
  124. final String column = "_data";
  125. final String[] projection = {
  126. column
  127. };
  128.  
  129. try {
  130. cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
  131. null);
  132. if (cursor != null && cursor.moveToFirst()) {
  133. final int column_index = cursor.getColumnIndexOrThrow(column);
  134. return cursor.getString(column_index);
  135. }
  136. } finally {
  137. if (cursor != null)
  138. cursor.close();
  139. }
  140. return null;
  141. }
  142.  
  143.  
  144. /**
  145. * @param uri The Uri to check.
  146. * @return 是否為 ExternalStorageProvider 類型的 uri
  147. * @author paulburke
  148. */
  149. public static boolean isExternalStorageDocument(Uri uri) {
  150. return "com.android.externalstorage.documents".equals(uri.getAuthority());
  151. }
  152.  
  153. /**
  154. * @param uri The Uri to check.
  155. * @return 是否為 DownloadsProvider 類型的 uri
  156. * @author paulburke
  157. */
  158. public static boolean isDownloadsDocument(Uri uri) {
  159. return "com.android.providers.downloads.documents".equals(uri.getAuthority());
  160. }
  161.  
  162. /**
  163. * @param uri The Uri to check.
  164. * @return MediaProvider 類型的 uri
  165. * @author paulburke
  166. */
  167. public static boolean isMediaDocument(Uri uri) {
  168. return "com.android.providers.media.documents".equals(uri.getAuthority());
  169. }
  170.  
  171. /**
  172. * @param uri The Uri to check.
  173. * @return 是否為 Google Photos 類型的 uri
  174. */
  175. public static boolean isGooglePhotosUri(Uri uri) {
  176. return "com.google.android.apps.photos.content".equals(uri.getAuthority());
  177. }
  178.  
  179. // 檢查檔案類型的小範例
  180.  
  181. /**
  182. * 檢查取回的檔案副檔名
  183. * @param path 檔案路徑
  184. * @return
  185. * 若檔案類型正確則回傳檔案名稱, 反之則回傳空字串
  186. * @throws EmptyFilePathException 路徑是空字串或是 null 物件
  187. * @throws FileNotFoundException 檔案不存在
  188. * @throws IllegalTrueTypeFontException 檔案類型不正確
  189. */
  190. public static String typefaceChecker(String path) throws EmptyFilePathException, FileNotFoundException, IllegalTrueTypeFontException {
  191. if( path == null || path.isEmpty() ){
  192. throw new EmptyFilePathException( "File path is empty" );
  193. }
  194.  
  195. File file = new File(path);
  196.  
  197. if( !file.exists() || !file.isFile() ) {
  198. throw new FileNotFoundException( "File path : " + path );
  199. }
  200.  
  201. String filename = file.getName();
  202. String ext = FileKit.getFileExt(filename);
  203.  
  204. if( !ext.equalsIgnoreCase(".ttf") ){
  205. throw new IllegalTrueTypeFontException( "File path : " + path + ", File name : " + filename + ", ext : " + ext );
  206. }
  207.  
  208. return filename;
  209. }
  210. }
各項資料連結
啟動檔案瀏覽器選擇檔案
Stackoverflow - Get real path from URI, Android KitKat new storage access framework
GitHub - aFileChooser

Android - 自訂 ViewGroup 以及 CustomView 的文字大小設定

2016-05-25 7:28 PM

在 CustomViewGroup 或 CustomView 內設置文字大小時

若直接取得 Dimension 再指定給文字顯示物件

會發現字體變得非常的大

  1. // 使用 dimension
  2. textSize = a.getDimension(R.styleable.StackedTextView_line1_textSize, 0);
  3.  
  4. textView.setTextSize(textSize);

其實是因為使用以上方式取得的大小設定其實是已經轉換過的大小

因此我們只要取得原始的大小設定再套用解析度設定即可

  1. // 使用 dimensionPixelSize
  2. textSize = a.getDimensionPixelSize(R.styleable.StackedTextView_line1_textSize, 0);
  3.  
  4. // 加入 TypedValue.COMPLEX_UNIT_PX 的設定
  5. textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
各項資料連結
Android Developers