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參數

暫時將一個半完整的項目作爲資源備用下,方便以後溫習和使用。


半完整源碼





發佈了66 篇原創文章 · 獲贊 16 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章