本文以 Android 9.0 爲準
概述
在《Android MediaProvider》 這篇文章中分析了 MediaProvider 的源碼,不過當多個外部存儲設備,並且存儲大量文件時,MediaProvider 會存在掃描慢的情況,爲了加快其掃描速度,修改策略爲:
- 在第一次外部存儲設備插入時,掃描數據存入數據庫,拔出時不刪除數據庫
- 針對多個外部存儲設備,存儲多個數據表
- 第二次插入外部存儲設備時,找到對應的數據庫,清理數據庫中的髒數據
當然,這種方式,在第一次掃描速度上,沒有進行優化,也沒有優化的空間,只能在第二次插拔上做文章,因爲原生的 MediaProvider 會在拔出外部存儲設備時刪除數據庫。
並且目前連接多個外部設備時,只操作一個外部數據庫(數據庫位置:/data/user/userid/com.android.providers.media/databases/external.db
),這樣就會導致數據量大,操作緩慢。
分析過程
通常來說,在 ContentProvider 中打開數據庫的操作,應該在 onCreate() 方法中進行的 。
@Override
public boolean onCreate() {
...
// DatabaseHelper緩存
mDatabases = new HashMap<String, DatabaseHelper>();
// 綁定內部存儲數據庫
attachVolume(INTERNAL_VOLUME);
...
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// 如果已掛載外部存儲,綁定外部存儲數據庫
attachVolume(EXTERNAL_VOLUME);
}
...
return true;
}
可以看到打開數據庫的位置在 attachVolume() 方法中:
/**
* Attach the database for a volume (internal or external).
* Does nothing if the volume is already attached, otherwise
* checks the volume ID and sets up the corresponding database.
*
* @param volume to attach, either {@link #INTERNAL_VOLUME} or {@link #EXTERNAL_VOLUME}.
* @return the content URI of the attached volume.
*/
private Uri attachVolume(String volume) {
...
// Update paths to reflect currently mounted volumes
// 更新路徑以反映當前裝載的卷
updateStoragePaths();
DatabaseHelper helper = null;
synchronized (mDatabases) {
helper = mDatabases.get(volume);
// 判斷是否已經attached過了
if (helper != null) {
if (EXTERNAL_VOLUME.equals(volume)) {
// 確保默認的文件夾已經被創建在掛載的主要存儲設備上,
// 對每個存儲卷只做一次這種操作,所以當用戶手動刪除時不會打擾
ensureDefaultFolders(helper, helper.getWritableDatabase());
}
return Uri.parse("content://media/" + volume);
}
Context context = getContext();
if (INTERNAL_VOLUME.equals(volume)) {
// 如果是內部存儲則直接實例化DatabaseHelper
helper = new DatabaseHelper(context, INTERNAL_DATABASE_NAME, true,
false, mObjectRemovedCallback);
} else if (EXTERNAL_VOLUME.equals(volume)) {
// 如果是外部存儲的操作,只獲取主要的外部卷ID
// Only extract FAT volume ID for primary public
final VolumeInfo vol = mStorageManager.getPrimaryPhysicalVolume();
if (vol != null) {
final StorageVolume actualVolume = mStorageManager.getPrimaryVolume();
final int volumeId = actualVolume.getFatVolumeId();
// Must check for failure!
// If the volume is not (yet) mounted, this will create a new
// external-ffffffff.db database instead of the one we expect. Then, if
// android.process.media is later killed and respawned, the real external
// database will be attached, containing stale records, or worse, be empty.
// 數據庫都是以類似 external-ffffffff.db 的形式命名的,
// 後面的 8 個 16 進制字符是該 SD 卡 FAT 分區的 Volume ID。
// 該 ID 是分區時決定的,只有重新分區或者手動改變纔會更改,
// 可以防止插入不同 SD 卡時數據庫衝突。
if (volumeId == -1) {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// This may happen if external storage was _just_ mounted. It may also
// happen if the volume ID is _actually_ 0xffffffff, in which case it
// must be changed since FileUtils::getFatVolumeId doesn't allow for
// that. It may also indicate that FileUtils::getFatVolumeId is broken
// (missing ioctl), which is also impossible to disambiguate.
// 已經掛載但是sd卡是隻讀狀態
Log.e(TAG, "Can't obtain external volume ID even though it's mounted.");
} else {
// 還沒有掛載
Log.i(TAG, "External volume is not (yet) mounted, cannot attach.");
}
throw new IllegalArgumentException("Can't obtain external volume ID for " +
volume + " volume.");
}
// generate database name based on volume ID
// 根據volume ID設置數據庫的名稱
String dbName = "external-" + Integer.toHexString(volumeId) + ".db";
// 創建外部存儲數據庫
helper = new DatabaseHelper(context, dbName, false,
false, mObjectRemovedCallback);
mVolumeId = volumeId;
} else {
// external database name should be EXTERNAL_DATABASE_NAME
// however earlier releases used the external-XXXXXXXX.db naming
// for devices without removable storage, and in that case we need to convert
// to this new convention
// 外部數據庫名稱應爲EXTERNAL_DATABASE_NAME
// 但是較早的版本對沒有可移動存儲的設備使用external-XXXXXXXX.db命名
// 在這種情況下,我們需要轉換爲新的約定
...
// 根據之前轉換的數據庫名,創建數據庫
helper = new DatabaseHelper(context, dbFile.getName(), false,
false, mObjectRemovedCallback);
}
} else {
throw new IllegalArgumentException("There is no volume named " + volume);
}
// 緩存起來,標識已經創建過了數據庫
mDatabases.put(volume, helper);
...
}
if (EXTERNAL_VOLUME.equals(volume)) {
// 給外部存儲創建默認的文件夾
ensureDefaultFolders(helper, helper.getWritableDatabase());
}
return Uri.parse("content://media/" + volume);
}
可以總結:
- 如果此存儲卷的 DatabaseHelper 已創建,則不執行任何操作。
- 對於內部存儲,數據存儲在 internal.db 中;
- 對於外部存儲,獲取主要的外部卷 ID,根據 ID 數據存儲在 external-XXXXXXXX.db 中;
- 對於較早版本中的外部存儲,數據保存在 external.db 中,需要轉換爲新的約定;
- 緩存 DatabaseHelper。
切入點是,對於外部存儲,創建 DatabaseHelper 時,直接使用參數傳遞過來的 volumeId,打開 external-XXXXXXXX.db。
代碼修改
一、MediaProvider
private Uri attachVolume(String volume) {
...
if (INTERNAL_VOLUME.equals(volume)) {
...
} else if (EXTERNAL_VOLUME.equals(volume)) {
// Only extract FAT volume ID for primary public
final VolumeInfo vol = mStorageManager.getPrimaryPhysicalVolume();
if (vol != null) {
final StorageVolume actualVolume = mStorageManager.getPrimaryVolume();
final int volumeId = actualVolume.getFatVolumeId();
...
} else {
...
}
} else {
throw new IllegalArgumentException("There is no volume named " + volume);
}
...
}
修改爲
private Uri attachVolume(String volume) {
...
if (INTERNAL_VOLUME.equals(volume)) {
...
} else {
final VolumeInfo vol = mStorageManager.getPrimaryPhysicalVolume();
if (vol != null) {
int volumeId = -1;
try {
volumeId = Integer.valueOf(volume);
} catch (NumberFormatException e) {
e.printStackTrace();
}
...
} else {
...
}
}
...
}
那麼 attachVolume(String volume) ,對於外部存儲傳入的 volume 就不應是 EXTERNAL_VOLUME 了,而應該是外部存儲的 volumeId。
volumeId 可以通過 StorageVolume 的 getFatVolumeId 方法獲取,本質就是將 UUID 轉換的 int 值,而 UUID 是一個長度爲 9 的字符串,類似與 “57E9-73B0”這樣。
繼而需要找到 attachVolume(String volume) 調用的地方,修改參數爲 volumeId,找到有兩個地方調用了:
1、onCreate() 方法中:
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
attachVolume(EXTERNAL_VOLUME);
}
可以通過 StorageManager.getStorageVolumes() 獲取全部的 StorageVolume,因此修改爲
final List<StorageVolume> storageVolumes = mStorageManager.getStorageVolumes();
String state;
for (StorageVolume storageVolume : storageVolumes) {
state = storageVolume.getState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
attachVolume(String.valueOf(storageVolume.getFatVolumeId()));
}
}
2、在 insertInternal() 方法中:
private Uri insertInternal(Uri uri, int match, ContentValues initialValues,
ArrayList<Long> notifyRowIds) {
...
switch (match) {
case VOLUMES:
{
String name = initialValues.getAsString("name");
Uri attachedVolume = attachVolume(name);
if (mMediaScannerVolume != null && mMediaScannerVolume.equals(name)) {
DatabaseHelper dbhelper = getDatabaseForUri(attachedVolume);
if (dbhelper == null) {
Log.e(TAG, "no database for attached volume " + attachedVolume);
} else {
dbhelper.mScanStartTime = SystemClock.currentTimeMicro();
}
}
return attachedVolume;
}
}
...
}
這個方法調用的源頭是在 MediaScannerService 中,下面分析掃描流程。
二、MediaScannerService
private void openDatabase(String volumeName) {
try {
ContentValues values = new ContentValues();
values.put("name", volumeName);
getContentResolver().insert(Uri.parse("content://media/"), values);
} catch (IllegalArgumentException ex) {
Log.w(TAG, "failed to open media database");
}
}
private void scan(String[] directories, String volumeName) {
Uri uri = Uri.parse("file://" + directories[0]);
// don't sleep while scanning
mWakeLock.acquire();
try {
ContentValues values = new ContentValues();
values.put(MediaStore.MEDIA_SCANNER_VOLUME, volumeName);
Uri scanUri = getContentResolver().insert(MediaStore.getMediaScannerUri(), values);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_STARTED, uri));
try {
if (volumeName.equals(MediaProvider.EXTERNAL_VOLUME)) {
openDatabase(volumeName);
}
try (MediaScanner scanner = new MediaScanner(this, volumeName)) {
scanner.scanDirectories(directories);
}
} catch (Exception e) {
Log.e(TAG, "exception in MediaScanner.scan()", e);
}
getContentResolver().delete(scanUri, null, null);
} finally {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_FINISHED, uri));
mWakeLock.release();
}
}
由於 volumeName 不再是 EXTERNAL_VOLUME,修改 openDatabase() 執行的判斷語句。
if (!volumeName.equals(MediaProvider.INTERNAL_VOLUME)) {
openDatabase(volumeName);
}
注意在調用 scan() 方法的地方,傳入的 directories 根據 volume 做了一個判斷,注意也要修正過來。
private final class ServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
...
String volume = arguments.getString("volume");
String[] directories = null;
if (MediaProvider.INTERNAL_VOLUME.equals(volume)) {
// scan internal media storage
directories = new String[] {
Environment.getRootDirectory() + "/media",
Environment.getOemDirectory() + "/media",
Environment.getProductDirectory() + "/media",
};
}
// 這裏的判斷要修改 start
/*else if (MediaProvider.EXTERNAL_VOLUME.equals(volume)) {*/
else {
// 這裏的判斷要修改 end
// scan external storage volumes
if (getSystemService(UserManager.class).isDemoUser()) {
directories = ArrayUtils.appendElement(String.class,
mExternalStoragePaths,
Environment.getDataPreloadsMediaDirectory().getAbsolutePath());
} else {
directories = mExternalStoragePaths;
}
}
if (directories != null) {
if (false) Log.d(TAG, "start scanning volume " + volume + ": "
+ Arrays.toString(directories));
scan(directories, volume);
if (false) Log.d(TAG, "done scanning volume " + volume);
}
...
}
}
找到 volumeName 賦值的源頭在 MediaScannerReceiver 中。
這裏猜測,存在一個優化點,掃描的路徑 directories,源碼中是全部的外部存儲路徑,爲了節省性能,directories 可以根據外部設備的 StorageVolume 的 getPath() 方法,進行單個路徑掃描。如果要處理的話,我們在這裏需要 MediaScannerReceiver 將路徑傳遞過來。(還未驗證,如果不行的話,就不要對 directories 進行修改了)。
三、MediaScannerReceiver
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final Uri uri = intent.getData();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
...
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
...
} else {
if (uri.getScheme().equals("file")) {
...
if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
// scan whenever any volume is mounted
scan(context, MediaProvider.EXTERNAL_VOLUME);
}
...
}
}
}
所以切入點就是,在接收 ACTION_MEDIA_MOUNTED 廣播的位置,獲取到 Uri,傳入 scan() 方法。
scan(context, uri.toString());
最後在回到 MediaScannerService 修改接收的參數 "volume"。
四、MediaScannerService
private final class ServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
...
String volume = arguments.getString("volume");
String[] directories = null;
if (MediaProvider.INTERNAL_VOLUME.equals(volume)) {
// scan internal media storage
directories = new String[] {
Environment.getRootDirectory() + "/media",
Environment.getOemDirectory() + "/media",
Environment.getProductDirectory() + "/media",
};
}
// 這裏需要修改 start
/*else if (MediaProvider.EXTERNAL_VOLUME.equals(volume)) {
// scan external storage volumes
if (getSystemService(UserManager.class).isDemoUser()) {
directories = ArrayUtils.appendElement(String.class,
mExternalStoragePaths,
Environment.getDataPreloadsMediaDirectory().getAbsolutePath());
} else {
directories = mExternalStoragePaths;
}
}*/
else {
boolean isSinglePath = false;// 標記單個路徑掃描
String[] singleStoragePath = new String[1];
try {
// Uri 轉換爲 File
File file = new File(new URI(volume));
// 根據 File 獲取 StorageVolume
StorageVolume storageVolume = mStorageManager.getStorageVolume(file);
if (storageVolume != null) {
// 重新賦值 volume 爲 volumeId
volume = String.valueOf(storageVolume.getFatVolumeId());
singleStoragePath[0] = storageVolume.getPath();
isSinglePath = true;
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
if (getSystemService(UserManager.class).isDemoUser()) {
if (isSinglePath) {
directories = ArrayUtils.appendElement(String.class,
singleStoragePath,
Environment.getDataPreloadsMediaDirectory().getAbsolutePath());
} else {
directories = ArrayUtils.appendElement(String.class,
mExternalStoragePaths,
Environment.getDataPreloadsMediaDirectory().getAbsolutePath());
}
} else {
if (isSinglePath) {
directories = singleStoragePath;
} else {
directories = mExternalStoragePaths;
}
}
}
// 這裏需要修改 end
if (directories != null) {
if (false) Log.d(TAG, "start scanning volume " + volume + ": "
+ Arrays.toString(directories));
scan(directories, volume);
if (false) Log.d(TAG, "done scanning volume " + volume);
}
...
}
}
五、ContentResolver
所有操作外部存儲的地方,增刪改查使用的 URI 中的 path 都要修改爲 volumeId,才能正常運行,而 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI 就不能使用了,看下 URI 的組成:
public static final Uri EXTERNAL_CONTENT_URI = getContentUri("external");
public static Uri getContentUri(String volumeName) {
return Uri.parse(CONTENT_AUTHORITY_SLASH + volumeName +
"/audio/media");
}
再看下 MediaProvider 中是根據 URI 的 path 中 volumeName 去獲取 DatabaseHelper:
private DatabaseHelper getDatabaseForUri(Uri uri) {
synchronized (mDatabases) {
if (uri.getPathSegments().size() >= 1) {
return mDatabases.get(uri.getPathSegments().get(0));
}
}
return null;
}
所以開發者使用中,只要傳入 volumeId 即可完成閉環。
MediaStore.Audio.Media.getContentUri(volumeId)
問題點 :
1、mVolumeId 需要處理嗎,添加多個到 MatrixCursor?
// Used temporarily (until we have unique media IDs) to get an identifier
// for the current sd card, so that the music app doesn't have to use the
// non-public getFatVolumeId method
if (table == FS_ID) {
MatrixCursor c = new MatrixCursor(new String[] {"fsid"});
c.addRow(new Integer[] {mVolumeId});
return c;
}
目前沒有處理,可以正常運行,先不處理該邏輯。
參考資料:
android 添加或者取消對於某種媒體文件格式的支持
Android源碼個個擊破之-多媒體掃描
Android媒體掃描詳細解析之一
Android媒體掃描詳細解析之二