1. 程式人生 > >Android呼叫系統自帶的檔案管理器,開啟指定路徑

Android呼叫系統自帶的檔案管理器,開啟指定路徑

一、開啟系統自帶的檔案管理器

       if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            showToast(R.string.msg_storage_nosdcard);
            return;
        }
        //獲取檔案下載路徑
        String compName = AppString.getCompanyName();
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + compName + "/OSC_DATA/";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //呼叫系統檔案管理器開啟指定路徑目錄
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setDataAndType(Uri.fromFile(dir.getParentFile()), "file/*.txt");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_CHOOSEFILE);
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){//選擇檔案返回
        super.onActivityResult(requestCode,resultCode,data);
        if(resultCode==RESULT_OK){
        switch(requestCode){
              case REQUEST_CHOOSEFILE:
              Uri uri=data.getData();
              chooseFilePath=FileChooseUtil.getInstance(this).getChooseFileResultPath(uri);
             Log.d(TAG,"選擇檔案返回:"+chooseFilePath);
              sendFileMessage(chooseFilePath);
              break;
        }
    }
}

二、工具類FileChooseUtil

public class FileChooseUtil {

    private Context context;
    private static FileChooseUtil util = null;

    private FileChooseUtil(Context context) {
        this.context = context;
    }

    public static FileChooseUtil getInstance(Context context) {
        if (util == null) {
            util = new FileChooseUtil(context);
        }
        return util;
    }

    /**
     * 對外介面  獲取uri對應的路徑
     *
     * @param uri
     * @return
     */
    public String getChooseFileResultPath(Uri uri) {
        String chooseFilePath = null;
        if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方應用開啟
            chooseFilePath = uri.getPath();
            Toast.makeText(context, chooseFilePath, Toast.LENGTH_SHORT).show();
            return chooseFilePath;
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以後
            chooseFilePath = getPath(context, uri);
        } else {//4.4以下下系統呼叫方法
            chooseFilePath = getRealPathFromURI(uri);
        }
        return chooseFilePath;
    }

    private String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }

    /**
     * 專為Android4.4設計的從Uri獲取檔案絕對路徑,以前的方法已不好使
     */
    @SuppressLint("NewApi")
    private String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            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)) {
                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 getDataColumn(context, uri, null, null);

        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            uri.getPath();

        }
        return null;
    }

    private 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()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private 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.
     */
    private 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.
     */
    private boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
}

完!!!

相關推薦

Android開啟系統檔案管理選擇指定型別的檔案

//呼叫系統檔案管理器開啟指定路徑目錄 Intent intent = new Intent(Intent.ACTION_GET_CONTENT); //intent.setDataAndType(Uri.fromFile(di

Android呼叫系統檔案管理開啟指定路徑

一、開啟系統自帶的檔案管理器 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { showToast(R.string.msg_

18、android呼叫系統檔案管理並返回選中檔案路徑

思路: 通過Android API呼叫系統自帶的檔案瀏覽器選取檔案獲得URI,然後將URI轉換成file,從而得到file。 import android.annotation.SuppressLint;import android.app.Activity;impo

Android6.0檔案管理無法開啟apk

Android從6.0開始在設定中自帶了一個檔案瀏覽器,在6.0之前系統是不自帶的,但是這個檔案管理器不能開啟apk檔案,不能安裝app。那是因為程式碼裡面沒有對APK檔案做識別處理,下面這個補丁可以幫你搞定. diff --git a/packages/Documents

Android呼叫系統的聯絡人介面

Intent intent = new Intent(); intent.setAction(Intent.ACTION_PICK); intent.setData(Contacts.People.CONTENT_URI); startActivityForResult(intent,     PICK_

Android呼叫系統的拍照功能出現Failure delivering result ResultInfo的問題

Intent getImageByCamera = new Intent(); getImageByCamera.setAction("android.media.action.IMAGE_CAPTURE"); xieWbActivity.startActivityForResult(getImageByCa

android 呼叫系統錄音實現語音錄製與播放

相關許可權:<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission> <uses-permission android:name="and

android開發中呼叫系統檔案選擇遇到的一些問題

1.呼叫系統的檔案瀏覽器然後進入檔案管理器選擇文字檔案後,直接回到檔案瀏覽器頁面造成文字檔案無法選擇 開始時候使用的方法: Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"

Android開發-呼叫系統軟體傳送郵件或分享文字-常用操作

一、實現效果     呼叫系統自帶的郵件軟體傳送郵件,同時設定收件人郵箱、郵件標題、和文字內容。 二、傳送郵件 Intent data=new Intent(Int

android WebView呼叫檔案管理點選返回鍵退出app的解決辦法

在清單檔案中,給含有該WebView的activity設定屬性: alwaysRetainTaskState屬性 和 configChanges屬性 這裡,我的是WebActivity: <activity android:name=".activity.We

android webview 執行時不呼叫系統瀏覽器

WebView mobView = new WebView(this); mobView.loadUrl("http://www.csdn.net"); WebSettings wSet = mobView.getSettings();     wSet.setJavaSc

開啟windows 系統FTP服務

信息服務 iis管理 ipv4 添加 net 系統 點擊 擴展性 匿名 一、添加功能 1.點擊添加刪除——>點擊打開或關閉windows功能2.展開Internet信息服務——>勾選FTP服務器(以及下面的FTP服務和FTP擴展性)3.展開web管理工具——&g

python 裝飾 晉級 系統的裝飾

計算 print def wrap time args turn per func #帶參數的裝飾器 #500個函數 # import time # FLAGE = False # def timmer_out(flag): # def timmer(func):

Android 呼叫系統安裝好的播放進行播放視訊

Intent intent = new Intent(Intent.ACTION_VIEW); String bpath = "file://" + videoPath; intent.setDataAndType(Uri.parse(bpath), "v

Python-Django(系統後臺管理

django (Python Web 框架) Django是一個開放原始碼的Web應用框架,由Python寫成。採用了MVC的框架模式,即模型M,檢視V和控制器C 我們系統環境中已經安裝了Python3.3了,Django需要繼續安裝,這裡

Android 開啟檔案管理並返回選中檔案的path

1: 點選觸發事件: Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.add

安卓呼叫系統分享功能分享文字分享大圖片仿好奇心日報分享長圖片(不用申請微信微博官方sdk就能直接分享)

當前安卓分享一共三種方式 1,呼叫安卓系統自帶分享功能(可以分享大圖) 2,呼叫微信,微博支付寶等自己的官方分享sdk 3,用友盟,shareSdk等整合好的sdk 由於公司業務要求,需要分享一些長圖,大圖到微信,微博等。由於微信微博自己的官方sdk對圖片有限制, 比如微博

iOS開發:呼叫系統相機以及獲取相簿照片的功能實現

在iOS開發過程中,經常用到的技術之一就是APP上傳圖片了,這個知識點雖然不難,但是上傳圖片的需求卻是各不相同,比如有些時候需要你一次性在相簿中同時多選指定數量的照片,而且選擇的照片數量不確定,有時候又需要呼叫系統相機拍照圖片。針對這種不同需求的上傳照片,只要掌

Android 使用系統的DownloadManager下載apk

首先扯點別的:清明節回了一趟黃島,去了學校看了看,也是物是人非了呀。酒也沒少喝,前天做了一夜的車早上9點多到上海,然後直接殺奔公司上班,也是沒誰了。 今天記錄一下DownloadManager的使用。參考連結會在文章末尾給出。先來個效果圖。 以下載一個萬

ios開發呼叫系統的分享

1.一般情況下提到分享,我們會想到去整合某些第三方的框架,例如很多第三方分享的集合例如友盟的,整合效果如下這裡只涉及到了常用的新浪、微信、及qq; 分享功能:三個平臺都比較寬鬆,只有有appid,都可以進行分享!登入功能:微信就比較苛刻了,需要進行開發者認證,其支付功能也需要