Android文件管理器選擇文件,獲得文件路徑URI轉(zhuǎn)File

記一次文件上傳引發(fā)的血案。

解決QQ瀏覽器com.tencent.mtt.fileprovider問題。

測試Demo


更新列表

日期 修改內(nèi)容
2019年7月2日 更新遇到的問題

前情描述:

使用系統(tǒng)文件管理器,選擇指定文件類型上傳。

基礎(chǔ)知識
  • MIME
  • 調(diào)起文件管理器
  • 指定瀏覽位置(路徑轉(zhuǎn)URI)
  • 設(shè)置多種文件類型
  • URI轉(zhuǎn)路徑
踩坑
  • com.tencent.mtt.fileprovider 問題

1. MIME

MIME (Multipurpose Internet Mail Extensions) 是描述消息內(nèi)容類型的因特網(wǎng)標(biāo)準(zhǔn)。

final String DOC = "application/msword";
final String XLS = "application/vnd.ms-excel";
final String PPT = "application/vnd.ms-powerpoint";
final String DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
final String XLSX = "application/x-excel";
final String XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
final String PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
final String PDF = "application/pdf";
final String MP4 = "video/mp4";
final String M3U8 = "application/x-mpegURL";

更多文件類型,自行百度

2. 調(diào)起文件管理器

  1. 所有類型文件

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    //任意類型文件
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent,1);
    
    //-------常用類型
        //圖片
    //intent.setType(“image/*”);
        //音頻
    //intent.setType(“audio/*”);
        //視頻
    //intent.setType(“video/*”); 
    //intent.setType(“video/*;image/*”);
    
    
  2. 系統(tǒng)的相冊

     Intent intent= new Intent(Intent.ACTION_PICK, null);
     intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
     startActivityForResult(intent, REQUEST_CODE_FILE); 
    
    

3. 指定瀏覽位置(路徑轉(zhuǎn)URI)

跳轉(zhuǎn)到指定路徑下,涉及到將路徑轉(zhuǎn)為URI,考慮Android版本區(qū)別

/**
 * file --> uri
 * @param context
 * @param file
 *
 * @return
 */
public static Uri getUriFromFile(Context context, File file) {
    if (context == null || file == null) {
        throw new NullPointerException();
    }
    Uri uri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        uri = FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileprovider", file);
    } else {
        uri = Uri.fromFile(file);
    }
    return uri;
}

由于7.0的升級還需要在AndroidManifest.xml中配置FileProvider

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

${applicationId}.fileprovider這個配置要記牢,后期遇到大坑就靠這個值了。

xml/file_paths 文件如下:

參考CSDN

<!--物理路徑相當(dāng)于Context.getFilesDir() + /path/-->
<files-path name="name" path="path" />

 <!--物理路徑相當(dāng)于Context.getCacheDir() + /path/-->
<cache-path name="name" path="path" /> 
 <!-- 物理路徑相當(dāng)于Environment.getExternalStorageDirectory() + /path/-->
<external-path name="name" path="path" />
 <!-- 物理路徑相當(dāng)于Context.getExternalFilesDir(String) + /path/-->
<external-files-path name="name" path="path" />
 <!-- 物理路徑相當(dāng)于Context.getExternalCacheDir() + /path/-->
<external-cache-path name="name" path="path" />

將文件路徑轉(zhuǎn)(使用微信下載目錄做測試)為URI后,設(shè)置到Intent中。

/**
 * 根據(jù)類型,加載文件選擇器
 */
private void chooseFileWithPath() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    //跳轉(zhuǎn)指定路徑,如果路徑不存在,切到sdcard
    //需要讀權(quán)限
    String path = getSDPath();
    if (!TextUtils.isEmpty(path)) {
        //使用微信下載目錄測試
        path = path + File.separator + "tencent/MicroMsg/Download";
        File file = new File(path);
        if (file.exists()) {
            //主要代碼
            intent.setDataAndType(FileUtil.getUriFromFile(this, new File(path)), "*/*");
        } else {
            intent.setType("*/*");
        }
    } else {
        intent.setType("*/*");
    }
    startActivityForResult(intent, REQUEST_CODE_FILE);
}

主要生效代碼:

Intent intent = new Intent(action,uri);
intent.setType("*/*");
startActivityForResult(intent, REQUEST_CODE_FILE);

或者

Intent intent = new Intent(action);
intent.setDataAndType(uri, "*/*");
startActivityForResult(intent, REQUEST_CODE_FILE);

特別注意:
指定目錄這種方式調(diào)起,在原生的管理器沒有其他注意的,但是如果用戶使用三方的管理器,例如QQ瀏覽器,那么在進(jìn)入到指定目錄下,不可以執(zhí)行返回操作。
例如:
如果路徑設(shè)置的是/sdcard/tencent/MicroMsg/Download,在進(jìn)入download目錄下,如果該目錄下沒有文件,那么想返回到其上層目錄MicroMsg,是不可以的。

4. 設(shè)置多種文件類型

通過intent.setType()方式設(shè)置的文件類型,只能生效一次,所以如果想只選擇doc、excel、pdt、ppt等辦公文檔,過濾掉其他文件,就不能使用intent .setType()方式,而是使用Intent.EXTRA_MIME_TYPES來傳值。


final String DOC = "application/msword";
final String XLS = "application/vnd.ms-excel";
final String PPT = "application/vnd.ms-powerpoint";
final String DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
final String XLSX = "application/x-excel";
final String XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
final String PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
final String PDF = "application/pdf";

/**
 * 多種文件類型
*/
private void chooseMoreTypes() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    String[] mimeTypes = {DOC, DOCX, PDF, PPT, PPTX, XLS, XLS1, XLSX};
    intent.setType("application/*");

    intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
    startActivityForResult(intent, REQUEST_CODE_FILE);
}

以上是準(zhǔn)備工作,調(diào)起文件管理器進(jìn)行選擇文件,對于一個Android開發(fā)者來說,以上步驟只是相當(dāng)于一小步,不要忘記適配。

接下來才是長征路。

5. URI轉(zhuǎn)路徑

在這一步主要解決的是將返回的URI轉(zhuǎn)換為File,大坑也往往就在這一步出現(xiàn)。

從網(wǎng)上能找到File轉(zhuǎn)File的代碼,但是百度出來的內(nèi)容,10篇有8篇是一樣的,剩下2篇不能看。

但是這8篇中幾乎都是相同的,沒有解決一個至關(guān)重要的問題QQ文件管理器

也可能是不會用搜索引擎吧。

上代碼

/**
 * 專為Android4.4設(shè)計的從Uri獲取文件絕對路徑,以前的方法已不好使
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

        //一些三方的文件瀏覽器會進(jìn)入到這個方法中,例如ES
        //QQ文件管理器不在此列

        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];
            }
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {
        ...
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
        ...
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore (and general)
        return getDataColumn(context, uri, null, null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
        ...
    }
    return null;
}

發(fā)現(xiàn)部手機(jī)會有第三方的文件管理器,如ES,QQ等目前只接觸到這兩種,不排除其他APP,相信大部分都是好同志,但不限于鵝廠大佬。

通過QQ瀏覽器選擇到的文件,則會報出不存在_data字段這個錯誤。

WTF

懵逼.jpg

返回的URI中uri.getAuthority()的值并不是自己在Manifest.xml中設(shè)置的${applicationId}.fileprovider而是com.tencent.mtt.fileprovider。

這時候,前面搜索到的文章,幾乎都沒有解決這個問題。

鑒于水平有限,被坑了半天后。

通過分析uri.getPath();的值。

content://com.tencent.mtt.fileprovider/QQBrowser/demo.mp4

寫下來如下代碼,如各位大佬有更好的解決方案,望轉(zhuǎn)告。

//判斷QQ文件管理器
if (isQQMediaDocument(uri)) {
    String path = uri.getPath();
    File fileDir = Environment.getExternalStorageDirectory();
    File file = new File(fileDir, path.substring("/QQBrowser".length(), path.length()));
    return file.exists() ? file.toString() : null;
}

測試通過機(jī)型: 魅族15,三星9300,mi6,oppoR9, 華為mate9

缺失代碼自行補(bǔ)齊,
主要類代碼FileUtil


其他問題

1. 文件類型設(shè)置

產(chǎn)品需求:

╔══════════════════════════════
║
║   上傳文件       上傳視頻
║
╚══════════════════════════════

要求: 1. 點(diǎn)擊視頻選擇mp4,2. 點(diǎn)擊文件選擇pdf、word等office文件。

在設(shè)置Intent的時候分為2種:

  • intent.setType("*/*")
    這種情況下,本意是想選擇office文檔。通過Intent.EXTRA_MIME_TYPES來限制文件類型,但是這種情況下,會出現(xiàn)第三方的文件管理器,而三方的一些情況下不會生效,所有文件都可以選擇。

我做的是,通過觀察MIME類型,我設(shè)置的是application/*第三方的文件管理圖標(biāo)隱藏掉了,只能通過系統(tǒng)的文件管理選擇文件。

image
image
  • intent.setType("video/mp4);
  1. 這種會顯示三方文件管理器,但是會過濾掉其他的文件,只有video類型的,如果有avi類型,那么還需要在onActivityResult中判斷文件后綴名。
  2. 系統(tǒng)的文件管理器會生效,只能選擇Intent.EXTRA_MIME_TYPES設(shè)置的類型。

2. 返回URI的問題

  • 從文件管理器選擇文件,返回的URI是content://com.android.externalstorage.documents/document/primary/update/A5679B1.mp4
  • 從『視頻』選擇文件,返回的URI是content://com.android.providers.media.documents/document/video:5188

遇到的問題:

判斷文件格式是否是我設(shè)置的類型,如果intent.setType("video/*");,但是只想要"mp4"格式的文件,那么在onActivityResult中通過返回的數(shù)據(jù)進(jìn)行判斷,前期想的是通過uri.getLastPathsegment(),判斷文件的后綴名,但是后來測試遇到了第二種情況,從『視頻』里選擇到文件,這時返回URI不符合規(guī)則了,所以偷懶是不行的,只能通過轉(zhuǎn)換,將源文件的名稱,判斷后綴名。

image

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容