这边文章主要来分析开机启动时候的多媒体文件扫描和如何修改系统默认铃声。
先来看开机启动时候的多多媒体文件扫描流程分析:
Android系统中,在开机的时候会去扫描内部存储器和外部存储器内的文件资源并将其添加到相应的数据库中,方便系统或者应用去引用相应的资源文件。
在android系统中,使用MediaScannerReceiver.java类来监听系统开机启动和SD卡挂载的广播,以此来执行相应的后续操作。
先来看MediaScannerReceiver.java在清单文件中的配置:
静态注册开机广播、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表示外部存储器;
对其他广播的操作。获取外部存储设备的路径,监听两种广播:一种是监听外部存储设备的挂载,另一种是接收指定文件的扫描。
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分析结束,其作用主要就是:
启动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 Service中onCreate()只会执行一次,但是onStartCommand可以重复调用,也就是说每当启动一次startService,就会调用一次onStartCommand。 @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()语句才是真正开始执行扫描文件操作。后面进行详细分析。
当文件扫描完成后,返回uri回到MediaScannerService.java中回调执行:
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发送msg到工作线程,调用scanFile()方法或者scan()方法;
4、在scanFile()方法或者scan()方法中构造MediaScanner.java对象,并调用scanSingleFile()方法或者scanDirectories()方法来进入到MediaScanner.java中开始进行扫描文件操作。