Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

讓 Activity 響應系統 Action:Android 對外文件導入的實現思路

編輯:關於 Android 程式設計

在文件管理器裡點開一個文件時,系統通常會彈出一個「選擇打開方式」的列表,讓你決定用哪個應用來處理它。

如果想讓自己的應用也出現在這個列表裡,關鍵在於告訴系統「我能處理哪些類型的文件」。這件事是在 AndroidManifest.xml 裡通過 intent-filter 聲明的。

一、在 Manifest 中聲明可處理的類型


    



    
    
    
    
    
    
    
    
    
    
    
    
    
    
    



    
    
    
    
    
    

第一組過濾器按 MIME 類型匹配,第二組則用 pathPattern 按後綴名匹配 file:// 協議的內容。兩者互補,覆蓋更多打開場景。

二、在 oncreate 中接收 Intent

Intent intent = this.getIntent();
int flags = intent.getFlags();

// 排除從最近任務歷史恢復的情況,避免重複導入
if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
    if (intent.getAction() != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
        if (SCHEME_FILE.equals(intent.getScheme())
                || SCHEME_CONTENT.equals(intent.getScheme())) {

            // 例如 mImportingUri = file:///storage/emulated/0/Vlog.xml
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            mImportingUri = intent.getData();

            InputStream is = null;
            try {
                is = getContentResolver().openInputStream(mImportingUri);
            } catch (Exception e) {
                Log.e(TAG, "open input stream failed", e);
            }

            if (mImportingUri != null
                    && SCHEME_FILE.equalsIgnoreCase(mImportingUri.getScheme())) {
                // file:// 協議:直接拷貝文件
                startToCopyFile(is);
            } else if (mImportingUri != null
                    && SCHEME_CONTENT.equalsIgnoreCase(mImportingUri.getScheme())) {
                // content:// 協議:先查詢元信息
                startCopyMedia(is);
            }
        }
    }
}

這裡要注意 FLAG_GRANT_READ_URI_PERMISSION。從 Android 4.4 開始,跨應用讀取 content:// URI 必須自帶這個標誌,否則會直接拋 SecurityException。

三、content:// 資源的元信息查詢

如果傳進來的是 content:// 協議,說明它可能來自 MediaStore 等內容提供者,此時文件名和大小不能直接從路徑拿,得通過 ContentResolver.query() 查。

private boolean startCopyMedia(InputStream is) {
    Cursor c = null;
    try {
        c = getContentResolver().query(mImportingUri,
                new String[] {
                    MediaStore.MediaColumns.DISPLAY_NAME,
                    MediaStore.MediaColumns.SIZE
                }, null, null, null);
        if (c != null && c.moveToFirst()) {
            int dnIndex = c.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
            fromFileName = c.getString(dnIndex);
            int sIndex = c.getColumnIndexOrThrow(MediaStore.MediaColumns.SIZE);
            fromFileSize = c.getLong(sIndex);
        }
    } catch (Exception e) {
        Log.e(TAG, "query media info failed", e);
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return true;
}

四、file:// 資源的異步拷貝

如果是普通文件,思路就簡單了:在 SD 卡下建一個臨時目錄,把文件拷進去,方便後續處理。拷貝放在後台線程裡做,避免阻塞 UI。

/** 確保目標文件的父目錄存在 */
public static void makesureFileExist(String path) {
    String separator = File.separator;
    int index = path.lastIndexOf(separator);
    path = path.substring(0, index);
    File f = new File(path);
    f.mkdirs();
    try {
        f.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/** 獲取 SD 卡根目錄 */
public static String getSDPath() {
    File sdDir = null;
    boolean sdCardExist = Environment.getExternalStorageState()
            .equals(android.os.Environment.MEDIA_MOUNTED);
    if (sdCardExist) {
        sdDir = Environment.getExternalStorageDirectory();
    }
    return sdDir != null ? sdDir.toString() : null;
}

private String getName(Uri uri) {
    String str = uri.toString();
    int index = str.lastIndexOf(File.separator);
    return str.substring(index, str.length());
}

private boolean startToCopyFile(InputStream is) {
    String fileName = getSDPath() + tmpPath + File.separator + getName(mImportingUri);
    makesureFileExist(fileName);
    File toFile = new File(fileName);
    new Thread(new CopyThread(is, toFile)).start();
    return true;
}

private class CopyThread implements Runnable {
    private File toFile;
    private InputStream fosfrom = null;

    public CopyThread(InputStream fosfrom, File toFile) {
        this.fosfrom = fosfrom;
        this.toFile = toFile;
    }

    @Override
    public void run() {
        try {
            TimeUnit.MILLISECONDS.sleep(800);
            if (this.fosfrom == null) {
                return;
            }
            FileOutputStream fosto = new FileOutputStream(toFile);
            byte[] bt = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosto.close();
        } catch (Exception e) {
            Log.e(TAG, "copy file failed", e);
        } finally {
            try {
                if (this.fosfrom != null) {
                    this.fosfrom.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

小結

整套流程可以概括為三步:在 Manifest 中用 intent-filter 聲明自己能處理的文件類型;在 Activity 裡判斷 ACTION_VIEW 與 scheme,拿到 Uri;最後根據 scheme 分別處理 content://(查元信息)和 file://(直接拷貝)兩種情況。這也正是各類「導入外部文件」功能的通用套路。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved