StorageManagerService的启动

Android2023年12月26日 pm2:30发布7个月前更新 3XCN.COM站长
0 0 0
广告也精彩
目录

前言

最近在看磁盘的挂载相关内容,涉及StorageManagerService,因此记录一下其的启动等相关内容,方便后续查阅和回顾。

个人流水文章,也就是只是方便自己而已。

Android P 源码分析

正文

直入正题。

SystemServer.java

我们知道SystemServer中做了如下内容。

  1. 初始化环境,比如时间,时区,语言等

  2. 准备主线程Looper

  3. 加载libandroid_servers.so库

  4. 初始化系统Context

  5. 创建SystemServiceManager

  6. 启动服务(引导服务,核心服务,其他服务)

  7. 进入Looper循环

今天涉及的是第6部分:启动服务(引导服务,核心服务,其他服务),而StorageManagerService的启动是属于其他服务

startOtherServices()
private static final String STORAGE_MANAGER_SERVICE_CLASS =
            "com.android.server.StorageManagerService$Lifecycle";
private static final String STORAGE_STATS_SERVICE_CLASS =
            "com.android.server.usage.StorageStatsService$Lifecycle";

private void startOtherServices() {
    if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
        if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
            try {
                //这个是ATC加入的一个条件
                //忽略,直接进入启动StorageManagerService$Lifecycle
                if (!sMtkSystemServerIns.startMtkStorageManagerService()) {
                    //启动StorageManagerService$Lifecycle
                    //重点
                    mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
                }
                storageManager = IStorageManager.Stub.asInterface(
                        ServiceManager.getService("mount"));
            } catch (Throwable e) {
                reportWtf("starting StorageManagerService", e);
            }
            try {
                //StorageStatsService$Lifecycle
                mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS);
            } catch (Throwable e) {
                reportWtf("starting StorageStatsService", e);
            }
        }
    }
}

我们这里只关心,其他的可以忽略。

mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);

startService()我们之前分析过,看《LocalServices和SystemService等简介》。

这里简单回顾一下哈,主要工作如下:

  1. 判断serviceClass是否继承SystemService

  2. 获取构造函数并实例化

  3. 添加到服务列表

  4. 调用start()方法

SystemServiceManager会添把StorageManagerService$Lifecycle添加到器服务列表中,这样可以方便管理启动的服务。

StorageManagerService.java

上面启动的是StorageManagerService$Lifecycle服务,也是个静态内部类,并继承于SystemService。

Lifecycle

这里主要关注onStart()

public static class Lifecycle extends SystemService {
    protected StorageManagerService mStorageManagerService;

    public Lifecycle(Context context) {
        super(context);
    }
    @Override
    public void onStart() {
        //创建mStorageManagerService对象
        mStorageManagerService = new StorageManagerService(getContext());
        //公开服务,就是添加到ServiceManager中
        publishBinderService("mount", mStorageManagerService);
        //调用mStorageManagerService的start()方法。
        mStorageManagerService.start();
    }
    @Override
    public void onBootPhase(int phase) {
        //这方法时SystemServiceManager中统一回调的,
        //也就是为啥一开始要添加到对应的服务列表的原因。
        if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
            mStorageManagerService.systemReady();
        } else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
            mStorageManagerService.bootCompleted();
        }
    }
    //略
}
StorageManagerService()

构造函数中主要是一些初始化,暂不关心,涉及到重新回头看就可以。

看上面条用的start()方法。

start()
public void start() {
    //重点
    connect();
    //略
}
connect()
private void connect() {
    //获取storaged的IBinder
    IBinder binder = ServiceManager.getService("storaged");
    if (binder != null) {
        try {
            //设置死亡监听,也就是Binder意外死亡时回调
            binder.linkToDeath(new DeathRecipient() {
                @Override
                public void binderDied() {
                    mStoraged = null;
                    connect();
                }
            }, 0);
        } catch (RemoteException e) {
            binder = null;
        }
    }
    
    if (binder != null) {
        //IStoraged mStoraged
        //获取IStoraged服务代理,可以跟服务端通信
        mStoraged = IStoraged.Stub.asInterface(binder);
    } else {
        Slog.w(TAG, "storaged not found; trying again");
    }
    //获取vold的IBinder
    binder = ServiceManager.getService("vold");
    if (binder != null) {
        try {
            //同上,死亡监听
            binder.linkToDeath(new DeathRecipient() {
                @Override
                public void binderDied() {
                    mVold = null;
                    connect();
                }
            }, 0);
        } catch (RemoteException e) {
            binder = null;
        }
    }
    if (binder != null) {
        //IVold mVold
        //获取IVold的服务代理,可以跟服务端通信
        mVold = IVold.Stub.asInterface(binder);
        try {
            //[重]设置监听
            mVold.setListener(mListener);
        } catch (RemoteException e) {
            mVold = null;
        }
    } else {
        Slog.w(TAG, "vold not found; trying again");
    }
    //如果上面两个服务代理都为null,延迟再获取一次,直到获取成功,
    if (mStoraged == null || mVold == null) {
        BackgroundThread.getHandler().postDelayed(() -> {
            connect();
        }, DateUtils.SECOND_IN_MILLIS);
    } else {
        //连接成功
        onDaemonConnected();
    }
}

这里是要获取mStoraged和mVold服务代理,也即是要跟对应的服务通信,通信成功或有主要做了如下事情:

  1. 设置监听mVold.setListener

  2. onDaemonConnected()

我们先看第二个,然后再看第一个。

onDaemonConnected()
public void onDaemonConnected() {
      //设置连接成功标志位
       mDaemonConnected = true;
       //发送H_DAEMON_CONNECTED
       mHandler.obtainMessage(H_DAEMON_CONNECTED).sendToTarget();
}

发送到handleMessage()中,然后执行handleDaemonConnected()

handleDaemonConnected()

这里主要做一些初始化,当然,里面初始化也要等系统是否启动完成等状态才可以初始化。这里懒得看啦。

private void handleSystemReady() {
    initIfReadyAndConnected();
    resetIfReadyAndConnected();

    // Start scheduling nominally-daily fstrim operations
    MountServiceIdler.scheduleIdlePass(mContext);

    // Toggle zram-enable system property in response to settings
    mContext.getContentResolver().registerContentObserver(
        Settings.Global.getUriFor(Settings.Global.ZRAM_ENABLED),
        false /*notifyForDescendants*/,
        new ContentObserver(null /* current thread */) {
            @Override
            public void onChange(boolean selfChange) {
                refreshZramSettings();
            }
        });
    refreshZramSettings();
}
IVoldListener

回到上面connect()中,获取到mVold服务代理后,设置了一个监听

mVold.setListener(mListener);

重点在mListener,这里是Vold服务层回调的接口,也就是跟Native层数据回调的重要方式。

这部分很重要,后续U盘的挂载和卸载等消息状态都是从下面方法中获取。具体看下面代码即可。

private final IVoldListener mListener = new IVoldListener.Stub() {
    @Override
    public void onDiskCreated(String diskId, int flags) {
        synchronized (mLock) {
            final String value = SystemProperties.get(StorageManager.PROP_ADOPTABLE);
            switch (value) {
                case "force_on":
                    flags |= DiskInfo.FLAG_ADOPTABLE;
                    break;
                case "force_off":
                    flags &= ~DiskInfo.FLAG_ADOPTABLE;
                    break;
            }
            mDisks.put(diskId, new DiskInfo(diskId, flags));
        }
    }

    @Override
    public void onDiskScanned(String diskId) {
        synchronized (mLock) {
            final DiskInfo disk = mDisks.get(diskId);
            if (disk != null) {
                onDiskScannedLocked(disk);
            }
        }
    }

    @Override
    public void onDiskMetadataChanged(String diskId, long sizeBytes, String label,
            String sysPath) {
        synchronized (mLock) {
            final DiskInfo disk = mDisks.get(diskId);
            if (disk != null) {
                disk.size = sizeBytes;
                disk.label = label;
                disk.sysPath = sysPath;
            }
        }
    }

    @Override
    public void onDiskDestroyed(String diskId) {
        synchronized (mLock) {
            final DiskInfo disk = mDisks.remove(diskId);
            if (disk != null) {
                mCallbacks.notifyDiskDestroyed(disk);
            }
        }
    }

    @Override
    public void onVolumeCreated(String volId, int type, String diskId, String partGuid) {
        synchronized (mLock) {
            final DiskInfo disk = mDisks.get(diskId);
            final VolumeInfo vol = new VolumeInfo(volId, type, disk, partGuid);
            mVolumes.put(volId, vol);
            onVolumeCreatedLocked(vol);
        }
    }

    @Override
    public void onVolumeStateChanged(String volId, int state) {
        //从VolumeBase.cpp的setState中调用这里的。
        //具体看Native层的VoldNativeService
        //VoldNativeService.setListener()
        synchronized (mLock) {
            final VolumeInfo vol = mVolumes.get(volId);
            Slog.e(TAG, "onVolumeStateChanged 222 vol : "+ vol);
            if (vol != null) {
                final int oldState = vol.state;
                final int newState = state;
                vol.state = newState;
                onVolumeStateChangedLocked(vol, oldState, newState);
            }
        }
    }

    @Override
    public void onVolumeSizeChange(String volId, String path) {
        synchronized (mLock) {
            final VolumeInfo vol = mVolumes.get(volId);
            if (vol != null) {
                final Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                File f = new File(vol.path);
                Uri contentUri = Uri.fromFile(f);
                intent.setData(contentUri);
                mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
             }
        }
    }

    @Override
    public void onVolumeMetadataChanged(String volId, String fsType, String fsUuid,
            String fsLabel) {
        synchronized (mLock) {
            final VolumeInfo vol = mVolumes.get(volId);
            if (vol != null) {
                vol.fsType = fsType;
                vol.fsUuid = fsUuid;
                vol.fsLabel = fsLabel;
            }
        }
    }

    @Override
    public void onVolumePathChanged(String volId, String path) {
        synchronized (mLock) {
            final VolumeInfo vol = mVolumes.get(volId);
            if (vol != null) {
                vol.path = path;
            }
        }
    }

    @Override
    public void onVolumeInternalPathChanged(String volId, String internalPath) {
        synchronized (mLock) {
            final VolumeInfo vol = mVolumes.get(volId);
            if (vol != null) {
                vol.internalPath = internalPath;
            }
        }
    }

    @Override
    public void onVolumeDestroyed(String volId) {
        synchronized (mLock) {
            mVolumes.remove(volId);
        }
    }
};

参考文章

  1. SystemServer的启动之一

  2. LocalServices和SystemService等简介

 历史上的今天

版权声明 1、 本站名称: 91易搜
2、 本站网址: 91es.com3xcn.com
3、 本站文章: 部分来源于网络,仅供站长学习和参考,若侵权请留言
广告也精彩

相关文章

广告也精彩

暂无评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

暂无评论...

网站升级中

公告

近期网站升级中,可能存在一些bug。欢迎反馈 https://www.91es.com/we.html

本站域名

本站域名 : 91es.com3xcn.com。本站邮箱 : 站长邮箱 i@oorr.cn,通知邮箱we@oorr.cn ,如有更新,请看公告 。