天天看點

android MediaStore 視訊以及視訊縮略圖問題記錄

描述:app的清單内需要顯示手機本地的照片、圖檔或者本地的視訊。我的方案是使用圖檔異步加載,使用的是Github上面大名頂頂的圖檔異步加載工具:universal-image-loader,基于這個前提,對于我來說就是使用圖檔的uri來顯示才最最友善。

解決問題的曆程:開始由于項目着急且對MediaStore确實有過頭疼的經曆,是以明智的選擇了直接開啟線程并通過檔案名的比對來尋找本地的視訊或者圖檔檔案。速度叫一個慢,效率叫一個低,總之一個字:弱。好在公司裡沒有人有異議。不過畢竟不是最優方案,頭上就像有一把達摩克利斯之劍,項目大難題都解決完了以後,殺了一個回馬槍。

目前解決方案:直接使用MediaStore來擷取資訊。用來顯示視訊和圖檔

MediaStore中提供的媒體資料有很多垃圾資料,媒體檔案已經不存在了,但是手機的媒體資料庫檔案卻依然還有該媒體的資訊。解決方案就是将每一個媒體檔案的路徑拿出來後,先去判斷該媒體檔案是否存在,不存在就跳過去,隻拿存在的資料。

這個問題不大,下一個問題比較頭疼。

就是有很多的視訊都沒有縮略圖... ...

找過兩個解決方案,其中方案以是使用:MediaScannerConnection。結果某些低端山寨手機上面沒辦法解決問題,而且問題趨勢與手機低端程度成正比關系。湊活點的手機能夠掃描出部分視訊縮略圖,低端到一定程度的時候幹脆就什麼都沒有掃描到。

整理了一下相關代碼:

package com.example.mediastoreproject.mediatools;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;

public class MediaScanner {

	private MediaScannerConnection mediaScanConn = null;
	private MusicSannerClient client = null;
	private String filePath = null;
	private String fileType = null;
	private String[] filePaths = null;

	public MediaScanner(Context context) {
		if (client == null) {
			client = new MusicSannerClient();
		}
		if (mediaScanConn == null) {
			mediaScanConn = new MediaScannerConnection(context, client);
		}
	}

	class MusicSannerClient implements
			MediaScannerConnection.MediaScannerConnectionClient {

		public void onMediaScannerConnected() {

			if (filePath != null) {
				mediaScanConn.scanFile(filePath, fileType);
			}

			if (filePaths != null) {
				for (String file : filePaths) {
					mediaScanConn.scanFile(file, fileType);
				}
			}

			filePath = null;
			fileType = null;
			filePaths = null;
		}

		public void onScanCompleted(String path, Uri uri) {
			mediaScanConn.disconnect();
		}

	}

	public void scanFile(String filepath, String fileType) {
		this.filePath = filepath;
		this.fileType = fileType;
		mediaScanConn.connect();
	}

	public void scanFile(String[] filePaths, String fileType) {
		this.filePaths = filePaths;
		this.fileType = fileType;
		mediaScanConn.connect();
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getFileType() {
		return fileType;
	}

	public void setFileType(String fileType) {
		this.fileType = fileType;
	}

}
           

找了不少資料都不怎麼樣,我要使用的是圖檔的uri,很多人都給出來擷取Bitmap的方法,還有一個項目甚至提供了一個看起來很不錯的方案,把所有的video的bitmap都生成一遍然後使用,程式推出後就bitmap就沒了。

最友善的就是讓android系統自己去針對指定的視訊生成縮略圖。其實方法就是

MediaStore.Video.Thumbnails.getThumbnail(ContentResolver cr, long origId, int kind, Options options)           

我在啟動程式的 時候進行檢查,對沒有縮略圖的視訊,記錄下其MediaStore.Video.Media._ID,這個就是getThumbnail方法中的 long origId參數

暫時将一個半完整的項目作為資源備用下,友善以後溫習和使用。

半完整源碼