Search

Andoird - 啟動檔案瀏覽器選擇檔案

2015-12-31 11:16 AM

App 開發真的比 Web 還來得辛苦啊...

抱怨結束

在開發時常常需要有選擇圖片、檔案等等的功能

這時就需要啟動外部 App (啟動檔案瀏覽器) 來獲得選取檔案後的結果

例如點擊按鈕後啟動檔案管理員,選擇檔案後取得檔案路徑

再使用檔案路徑完成上傳檔案啦~ 圖片編輯等等的後續處理

搜尋 Intent file browser 可以得到很多資訊喔

接下來就開始介紹如何實現這項功能

4.4 版本以上由於 Android 修改了檔案的存取方式

請搭配這篇教學的方法使用 KitKat 以上版本從 URI 取得檔案實體路徑

程式碼範例
  1. // 外部 App 回傳結果的類型判斷碼
  2. private static final int FILE_SELECT_CODE = 0;
  3.  
  4. // 在按鈕上監聽點擊事件
  5. settingsTypefaceButton.setOnClickListener(new View.OnClickListener() {
  6. @Override
  7. public void onClick(View v) {
  8. fileBrowserIntent();
  9. }
  10. });
  11.  
  12. /**
  13. * 啟動外部 App 的檔案管理員
  14. */
  15. private void fileBrowserIntent(){
  16. Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
  17. // 設定 MIME Type 但這裡是沒用的 加個心安而已
  18. intent.setType("application/font-sfnt");
  19. intent.addCategory(Intent.CATEGORY_OPENABLE);
  20.  
  21. try {
  22. startActivityForResult( Intent.createChooser(intent, "選擇字型"), FILE_SELECT_CODE );
  23. } catch (android.content.ActivityNotFoundException ex) {
  24. // 若使用者沒有安裝檔案瀏覽器的 App 則顯示提示訊息
  25. Toast.makeText(this, "沒有檔案瀏覽器 是沒辦法選擇字型的", Toast.LENGTH_SHORT).show();
  26. }
  27. }
  28.  
  29. /**
  30. * 使用者選擇的結果將會作為參數傳遞至此
  31. * @param requestCode 發出要求的代碼, 用以確定是取得何種結果
  32. * @param resultCode 回傳結果的代碼, 用已確定是否請求成功
  33. * @param data 回傳的資料
  34. */
  35. @Override
  36. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  37. switch (requestCode) {
  38. // 檔案選擇代碼
  39. case FILE_SELECT_CODE:
  40. // 請求確認返回
  41. if (resultCode == RESULT_OK) {
  42. // 取得檔案路徑 Uri
  43. Uri uri = data.getData();
  44. // 取得路徑
  45. String path = null;
  46. try {
  47. path = FileUtils.getPath(this, uri);
  48. } catch (URISyntaxException e) {
  49. Toast.makeText(this, "檔案不對勁!", Toast.LENGTH_SHORT).show();
  50. logger.error("Get file path failed.", e);
  51. return;
  52. }
  53.  
  54. // 檢查檔案類型
  55. String filename = FileUtils.typefaceChecker(path);
  56.  
  57. if( filename.isEmpty() ){
  58. Toast.makeText(this, "檔案不對勁!", Toast.LENGTH_SHORT).show();
  59. return;
  60. }
  61.  
  62. // Do something here...
  63. }
  64. break;
  65. }
  66. super.onActivityResult(requestCode, resultCode, data);
  67. }

眼尖的人就注意到了,FileUtils 是啥? 為什麼我沒有!!!

為什麼網路教學老是缺東缺西的啊!!! 崩潰啊啊啊啊啊啊啊啊!!!

我說寧王先別急著發飆啊

因為那是需要自己建立的 Class

原始碼如下

  1. import android.content.Context;
  2. import android.database.Cursor;
  3. import android.net.Uri;
  4. import cmc.toolkit.FileKit;
  5.  
  6. import java.io.File;
  7. import java.net.URISyntaxException;
  8.  
  9. public class FileUtils {
  10.  
  11. /**
  12. * 由外部 Activity 回傳的資料取得檔案路徑
  13. * @param context Activity
  14. * @param uri Uri
  15. * @return
  16. * 檔案路徑
  17. * @throws URISyntaxException
  18. */
  19. public static String getPath(Context context, Uri uri) throws URISyntaxException {
  20. if ("content".equalsIgnoreCase(uri.getScheme())) {
  21. String[] projection = { "_data" };
  22. Cursor cursor = null;
  23.  
  24. try {
  25. cursor = context.getContentResolver().query(uri, projection, null, null, null);
  26. int column_index = cursor.getColumnIndexOrThrow("_data");
  27. if (cursor.moveToFirst()) {
  28. return cursor.getString(column_index);
  29. }
  30. } catch (Exception e) {
  31. // Do nothing
  32. }
  33. finally {
  34. if( cursor != null ) cursor.close();
  35. }
  36. }
  37. else if ("file".equalsIgnoreCase(uri.getScheme())) {
  38. return uri.getPath();
  39. }
  40.  
  41. return null;
  42. }
  43.  
  44. /**
  45. * 檢查取回的檔案副檔名
  46. * @param path 檔案路徑
  47. * @return
  48. * 若檔案類型正確則回傳檔案名稱, 反之則回傳空字串
  49. */
  50. public static String typefaceChecker(String path){
  51. if( path == null || path.isEmpty() ) return "";
  52.  
  53. File file = new File(path);
  54.  
  55. if( !file.exists() || !file.isFile() ) {
  56. return "";
  57. }
  58.  
  59. String filename = file.getName();
  60. String ext = FileKit.getFileExt(filename);
  61.  
  62. if( !ext.equalsIgnoreCase(".ttf") ){
  63. return "";
  64. }
  65.  
  66. return filename;
  67. }
  68.  
  69. }
  70.  
  71.  
  72.  
  73. // 一併附上取得副檔名的程式碼, FileKit 是我剛學 Java 時自己寫的小工具
  74.  
  75. public static String getFileExt(String fileName) {
  76. int dotIndex = fileName.lastIndexOf(".");
  77. return dotIndex == -1 ? "" : fileName.substring(dotIndex);
  78. }
各項資料連結
Stackoverflow - Android file chooser

1 comment: