この記事では、主に起動時のマルチメディアファイルスキャンと、システムのデフォルトの着信音を変更する方法を分析します。
まず、起動時のマルチメディアファイルスキャンプロセスの分析を見てみましょう。
Androidシステムでは、内部ストレージと外部ストレージのファイルリソースがスキャンされ、起動時に対応するデータベースに追加されるため、システムまたはアプリケーションは対応するリソースファイルを参照できます。
Androidシステムでは、MediaScannerReceiver.javaクラスを使用して、システムの起動とSDカードのマウントのブロードキャストを監視し、対応するフォローアップ操作を実行します。
まず、マニフェストファイルのMediaScannerReceiver.javaの構成を確認します。
<receiver android:name="MediaScannerReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<data android:scheme="file" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MEDIA_UNMOUNTED" />
<data android:scheme="file" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MEDIA_SCANNER_SCAN_FILE" />
<data android:scheme="file" />
</intent-filter>
</receiver>
静的登録ブートブロードキャスト、SDカードのマウント/アンマウントブロードキャスト、ファイルスキャンブロードキャストなど。
MediaScannerReceiver.javaはBroadcastReceiverを継承しています。まず、onReceive()メソッドを確認してください。
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final Uri uri = intent.getData();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
// Scan both internal and external storage
scan(context, MediaProvider.INTERNAL_VOLUME);
scan(context, MediaProvider.EXTERNAL_VOLUME);
} else {
if (uri.getScheme().equals("file")) {
// handle intents related to external storage
String path = uri.getPath();
String externalStoragePath = Environment.getExternalStorageDirectory().getPath();
String legacyPath = Environment.getLegacyExternalStorageDirectory().getPath();
try {
path = new File(path).getCanonicalPath();
} catch (IOException e) {
Log.e(TAG, "couldn't canonicalize " + path);
return;
}
if (path.startsWith(legacyPath)) {
path = externalStoragePath + path.substring(legacyPath.length());
}
Log.d(TAG, "action: " + action + " path: " + path);
if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
// scan whenever any volume is mounted
scan(context, MediaProvider.EXTERNAL_VOLUME);
} else if (Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action) &&
path != null && path.startsWith(externalStoragePath + "/")) {
scanFile(context, path);
}
}
}
}
Intent.ACTION_BOOT_COMPLETED事件:
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
// Scan both internal and external storage
scan(context, MediaProvider.INTERNAL_VOLUME);
scan(context, MediaProvider.EXTERNAL_VOLUME);
}
scan()メソッドを呼び出します。MediaProvider.INTERNAL_VOLUMEは内部ストレージを意味し、MediaProvider.EXTERNAL_VOLUMEは外部ストレージを意味します。
他の放送の操作。外部ストレージデバイスのパスを取得し、2つのブロードキャストを監視します。1つは外部ストレージデバイスのマウントを監視するためのもので、もう1つは指定されたファイルのスキャンを受信するためのものです。
if (uri.getScheme().equals("file")) {
// handle intents related to external storage
String path = uri.getPath();
String externalStoragePath = Environment.getExternalStorageDirectory().getPath();
String legacyPath = Environment.getLegacyExternalStorageDirectory().getPath();
try {
path = new File(path).getCanonicalPath();
} catch (IOException e) {
Log.e(TAG, "couldn't canonicalize " + path);
return;
}
if (path.startsWith(legacyPath)) {
path = externalStoragePath + path.substring(legacyPath.length());
}
Log.d(TAG, "action: " + action + " path: " + path);
if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
// scan whenever any volume is mounted
scan(context, MediaProvider.EXTERNAL_VOLUME);
} else if (Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action) &&
path != null && path.startsWith(externalStoragePath + "/")) {
scanFile(context, path);
}
}
1.外部ストレージパスを取得します。
2.受信したブロードキャストのタイプを判別します。SDカードマウントブロードキャストを受信した場合、パラメーターはMediaProvider.EXTERNAL_VOLUMEで、scan()メソッドを呼び出します。ファイルスキャンブロードキャストを受信した場合、パラメーターはファイルパスであり、scanFile()メソッドが呼び出されます。
private void scan(Context context, String volume) {
Bundle args = new Bundle();
args.putString("volume", volume);
context.startService(
new Intent(context, MediaScannerService.class).putExtras(args));
}
private void scanFile(Context context, String path) {
Bundle args = new Bundle();
args.putString("filepath", path);
context.startService(
new Intent(context, MediaScannerService.class).putExtras(args));
}
この時点で、MediaScannerReceiver分析は終了し、その主な機能は次のとおりです。
(1)ブロードキャストの受信
(2)対応するス
キャンパスの構築 (3)MediaScannerServiceの開始
MediaScannerServiceを開始します。このクラスはServiceを継承し、Runnableインターフェイスを実装します。まずMediaScannerService.javaのonCreateメソッドを確認します。
public void onCreate()
{
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
StorageManager storageManager = (StorageManager)getSystemService(Context.STORAGE_SERVICE);
mExternalStoragePaths = storageManager.getVolumePaths();
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block.
Thread thr = new Thread(null, this, "MediaScannerService");
thr.start();
}
1.CPUウェイクロックをインスタンス化します。
2.外部ストレージパスを取得します。
3.スレッドを開始してrun()メソッドを呼び出し、メッセージキューを開き、mServiceHandlerメッセージハンドラーを作成します。
public void run()
{
// reduce priority below other background threads to avoid interfering
// with other services at boot time.
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND +
Process.THREAD_PRIORITY_LESS_FAVORABLE);
Looper.prepare();
mServiceLooper = Looper.myLooper();
mServiceHandler = new ServiceHandler();
Looper.loop();
}
onStartCommandメソッドを見てみましょう
Androidサービスでは、onCreate()は1回だけ実行されますが、onStartCommandは繰り返し呼び出すことができます。つまり、startServiceが開始されるたびに、onStartCommandが1回呼び出されます。 @Override
public int onStartCommand(Intent intent, int flags, int startId)
{
while (mServiceHandler == null) {
synchronized (this) {
try {
wait(100);
} catch (InterruptedException e) {
}
}
}
if (intent == null) {
Log.e(TAG, "Intent is null in onStartCommand: ",
new NullPointerException());
return Service.START_NOT_STICKY;
}
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent.getExtras();
mServiceHandler.sendMessage(msg);
// Try again later if we are killed before we can finish scanning.
return Service.START_REDELIVER_INTENT;
}
1.mServiceHandlerメッセージハンドラーの作成が完了するのを待ちます。
2.着信パラメータに従ってmsgをカプセル化し、メッセージプロセッサmServiceHandlerによる処理のためにメッセージをワーカースレッドに送信します。
private final class ServiceHandler extends Handler{
@Override
public void handleMessage(Message msg){
Bundle arguments = (Bundle) msg.obj;
//获取参数,判断是指定路径还是整个存储磁盘
String filePath = arguments.getString("filepath");
try {
if (filePath != null) {//扫描的是指定路径
IBinder binder = arguments.getIBinder("listener");
IMediaScannerListener listener =
(binder == null ? null : IMediaScannerListener.Stub.asInterface(binder));
Uri uri = null;
try {
//扫描
uri = scanFile(filePath, arguments.getString("mimetype"));
} catch (Exception e) {
Log.e(TAG, "Exception scanning file", e);
}
if (listener != null) {
//扫描完成后回调scanCompleted()方法
listener.scanCompleted(filePath, uri);
}
} else {//扫描整个磁盘
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",
};
}
else if (MediaProvider.EXTERNAL_VOLUME.equals(volume)) {//外部存储器
// scan external storage volumes
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);
}
}
} catch (Exception e) {
Log.e(TAG, "Exception in handleMessage", e);
}
//扫描完成后,停止对应的服务
stopSelf(msg.arg1);
}
};
パススキャンを指定するかどうかを決定します。指定する場合は、scanFile()メソッドを呼び出します。指定しない場合は、scan()メソッドを呼び出してスキャンします。スキャンが完了したら、対応するサービスを停止します。
まず、指定されたパス、scanFile()メソッドでスキャンを確認します。
private Uri scanFile(String path, String mimeType) {
String volumeName = MediaProvider.EXTERNAL_VOLUME;
openDatabase(volumeName);
MediaScanner scanner = createMediaScanner();
try {
// make sure the file path is in canonical form
String canonicalPath = new File(path).getCanonicalPath();
return scanner.scanSingleFile(canonicalPath, volumeName, mimeType);
} catch (Exception e) {
Log.e(TAG, "bad path " + path + " in scanFile()", e);
return null;
}
}
1. createMediaScanner()メソッドを呼び出して、MediaScannerオブジェクトを作成します。
private MediaScanner createMediaScanner() {
//创建MediaScanner对象
MediaScanner scanner = new MediaScanner(this);
//获取当前系统的语言信息
Locale locale = getResources().getConfiguration().locale;
if (locale != null) {
String language = locale.getLanguage();
String country = locale.getCountry();
String localeString = null;
//为MediaScanner设置语言环境
if (language != null) {
if (country != null) {
scanner.setLocale(language + "_" + country);
} else {
scanner.setLocale(language);
}
}
}
return scanner;
}
2. MediaScanner.javaオブジェクトのscanSingleFile()メソッドを呼び出して、ファイルをスキャンします。
// this function is used to scan a single file
public Uri scanSingleFile(String path, String volumeName, String mimeType) {
try {
initialize(volumeName);
prescan(path, true);
File file = new File(path);
if (!file.exists()) {
return null;
}
// lastModified is in milliseconds on Files.
long lastModifiedSeconds = file.lastModified() / 1000;
// always scan the file, so we can return the content://media Uri for existing files
return mClient.doScanFile(path, mimeType, lastModifiedSeconds, file.length(),
false, true, MediaScanner.isNoMediaPath(path));
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in MediaScanner.scanFile()", e);
return null;
} finally {
releaseResources();
}
}
このメソッドは単一のファイルをスキャンするために使用されます。initialize()メソッドとprescan()メソッドは、スキャン前にいくつかの初期化および準備操作を実行するために使用されます。mClient.doScanFile()ステートメントは、ファイル操作のスキャンの実際の開始です。詳細な分析は後で行われます。
ファイルスキャンが完了したら、MediaScannerService.javaのコールバック実行にURIを戻します。
if (listener != null) {
listener.scanCompleted(filePath, uri);
}
これまでに、指定されたパスでのスキャンプロセス分析が完了しました。
不特定のパスの下でのスキャン、つまりディスクディレクトリ内のマルチメディアファイルのスキャンを見てみましょう。これは本質的にスキャンです。
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);
//获取MediaProvider的ContentResolver,并执行插入操作
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);
}
//构建MediaScanner对象,开始扫描目录
MediaScanner scanner = createMediaScanner();
scanner.scanDirectories(directories, volumeName);
} 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));
//释放cpu锁
mWakeLock.release();
}
}
1.CPUウェイクロックを申請します。
2. MediaProviderのContentResolverを取得し、挿入操作を実行します。
3.ブートブロードキャストを送信します。
4.それが外部メモリであるかどうかを判別し、insert(Uri.parse( "content:// media /")、values)操作を実行します。
5. MediaScannerオブジェクトを作成し、現在のロケールに従ってMediaScannerを設定し、ディレクトリのスキャンを開始します。
6.scanUriに従って削除およびクリーンアップします。
7.スキャン完了ブロードキャストを送信し、CPUウェイクアップロックを解除します。
MediaScannerService.javaのonStartCommand()プロセスが終了します。
この時点で、MediaScanner.javaと入力します。このクラスはスキャン操作の実際の実現であり、データベースを挿入する操作を実行します。このカテゴリの長さと重要性のため、後で個別に分析します。
総括する:
1. MediaScannerReceiver.javaでブートブロードキャストを監視すると、SDカードがブロードキャストでハングします。
2.ブロードキャストを受信した後、MediaScannerService.javaを起動します。
3. MediaScannerService.javaのワーカースレッドにメッセージを送信し、scanFile()メソッドまたはscan()メソッドを呼び出します。
4. scanFile()メソッドまたはscan()メソッドでMediaScanner.javaオブジェクトを作成し、scanSingleFile()メソッドまたはscanDirectories()メソッドを呼び出してMediaScanner.javaに入り、ファイルのスキャン操作を開始します。