Android MediaScannerService源码分析

本文详细分析了Android MediaScannerService (MSS) 的工作原理,从初始化过程到核心方法如`onCreate()`、`run()`、`onStartCommand()`、`scanFile()`和`scan()`。MSS在后台运行,主要通过ServiceHandler处理任务,并调用MediaScanner进行文件扫描。当接收到广播时,MSS负责扫描SDCard上的文件和目录。
摘要由CSDN通过智能技术生成

1. 简介

MediaScannerService简称MSS, 是一个运行于后台的Service, 实现了Runnable接口.
MediaScannerReceiver接收广播, 然后由MSS具体完成工作. MSS中主要工作在ServiceHandler实现

2. 初始化

这里写图片描述

2.1 onCreate()

完成2项工作
(1)启动线程

        // 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();

之后会调用run方法, 参见2.2
(2) 注册/监听SDCard 卸载事件

        IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_EJECT);
        filter.addDataScheme("file");
        filter.setPriority(100);
        registerReceiver(mUnmountReceiver, filter);

2.2 run

MSS实现Runable的run方法, onCreate时会调用此方法启动线程.
run方法主要功能就是启动ServiceHandler

    public void run()
    {
        Looper.prepare();

        mServiceLooper = Looper.myLooper();
        mServiceHandler = new ServiceHandler();

        /// M: reduce thread priority after ServiceHandler have been created to avoid cpu starvation
        /// which may cause ANR because create service handler too slow.
        // 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.loop();
    }

2.3 onStartCommand

(1) 等待ServiceHandler启动

        while (mServiceHandler == null) {
            synchronized (this) {
                try {
                    wait(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值