AMS管理android四大组件

ActivityManageService管理四大组件

AMS是android中SystemServer进程中的一个线程,单从名字看以为只是管理Activity ,其实AMS是管理四大组件运行状态的系统服务线程。
《AMS管理android四大组件》

1.SystemServer进程启动AMS

SystemServer.java中的关键源码,如下:

private void startBootstrapServices() {
            // Activity manager runs the show.
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
}

SystemServiceManager.startService(Class clazz)通过反射的技术的启动Service,关键源码如下

 public <T extends SystemService> T startService(Class<T> serviceClass) {
       //...
            Constructor<T> constructor = serviceClass.getConstructor(Context.class);
            service = constructor.newInstance(mContext);
        //...        
        // Register it.
        mServices.add(service);

        // Start it.
        try {
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + name
                    + ": onStart threw an exception", ex);
        }
        return service;
    }

SystemServiceManager.startService入参是ActivityManagerService.Lifecycle.class,追踪源码,如下

    public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            mService = new ActivityManagerService(context);
        }

        @Override
        public void onStart() {
            mService.start();
        }

        public ActivityManagerService getService() {
            return mService;
        }
    }

从源码可以知道Lifecycle封装了AMS还继承了SystemService的功能。Lifecycle构造函数创建了一个AMS对象,调用了AMS的构造函数,关键源码如下:

 public ActivityManagerService(Context systemContext) {
        mContext = systemContext;
        mFactoryTest = FactoryTest.getMode();
        mSystemThread = ActivityThread.currentActivityThread();
        //创建一个 ServiceThread,TAG
        mHandlerThread = new ServiceThread(TAG,
                android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        //对应的Handler
        mHandler = new MainHandler(mHandlerThread.getLooper());

这里SystemServer主线程调用Thread.start真正启动AMS线程ServiceThread。

2.AMS线程采用循环机制来处理同一进程内的请求

ServiceThread是HandlerThread的子类,其run方法源码如下

public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

这源码可以知道,AMS线程也是采用Hander,Looper,MessageQueue的循环机制来处理客户的请求。

3.循环机制处理客户的请求类型

AMS是通过mHandler来处理客户请求,查看其源码

final class MainHandler extends Handler {
        public MainHandler(Looper looper) {
            super(looper, null, true);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SHOW_ERROR_MSG: {
            case SHOW_NOT_RESPONDING_MSG: {
            case SHOW_STRICT_MODE_VIOLATION_MSG: {
            case SHOW_FACTORY_ERROR_MSG: {
            case WAIT_FOR_DEBUGGER_MSG: {
            case SERVICE_TIMEOUT_MSG: {
            case UPDATE_TIME_ZONE: {
            case CLEAR_DNS_CACHE_MSG: {
            case UPDATE_HTTP_PROXY_MSG: {
            case SHOW_UID_ERROR_MSG: {
            case IM_FEELING_LUCKY_MSG: {
            case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
            case FINALIZE_PENDING_INTENT_MSG: {
            case CANCEL_HEAVY_NOTIFICATION_MSG: {
            case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
            case SHOW_COMPAT_MODE_DIALOG_MSG: {
            case DISPATCH_PROCESSES_CHANGED: {
            case DISPATCH_PROCESS_DIED: {
            case START_USER_SWITCH_MSG: {
            case REPORT_USER_SWITCH_MSG: {
            case CONTINUE_USER_SWITCH_MSG: {
            case USER_SWITCH_TIMEOUT_MSG: {
            case IMMERSIVE_MODE_LOCK_MSG: {
            case PERSIST_URI_GRANTS_MSG: {
            case REQUEST_ALL_PSS_MSG: {
            case START_PROFILES_MSG: {
            case UPDATE_TIME: {
            case SYSTEM_USER_START_MSG: {
            case SYSTEM_USER_CURRENT_MSG: {
            case ENTER_ANIMATION_COMPLETE_MSG: {
            case FINISH_BOOTING_MSG: {
            case SEND_LOCALE_TO_MOUNT_DAEMON_MSG: {
        }

4.AMS向ServiceManager登记Binder

ActivityManagerService向ServiceManager登记多种Binder Server。包括“actvity”、“meminfo”、“gfxinfo”、“dbinfo”。其中最主要的是“actvity” Binder Server,

 // Set up the Application instance for the system process and get started.
        mActivityManagerService.setSystemProcess(); 

 public void setSystemProcess() {
        try {
            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
            ServiceManager.addService("meminfo", new MemBinder(this));
            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
            ServiceManager.addService("dbinfo", new DbBinder(this));
            if (MONITOR_CPU_USAGE) {
                ServiceManager.addService("cpuinfo", new CpuBinder(this));
            }
            ServiceManager.addService("permission", new PermissionController(this));

这是一种实名的Binder Server,其他进程可以向ServiceManager查询该Binder的引用,进而跟AMS通信,例如启动activity、service等。

5.四大组件都是由AMS管理的

AMS的职责不仅仅是Activity,还包括Service、BroadCast Receiver、ContentProvider。
应用程序通过Binder机制与AMS通信,进而由AMS管理四大组件,包括启动、停止等。

public final class ActivityManagerService extends ActivityManagerNative
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
        //...
        public int startActivity(...)  {...}
        public final void activityStopped(...) {...}
        public ComponentName startService(...){...}
        public Intent registerReceiver(...) {...}
        public final ContentProviderHolder getContentProvider(...}
        //...

}

6.ActivityRecord对应一个Activity

系统中每一个Activity都需要在AMS中做记录,对应一个ActivityRecord,ActivityRecord记录着对应activity的信息,其源码如下

/** * An entry in the history stack, representing an activity. */
final class ActivityRecord {
    final ActivityManagerService service; // owner
    final IApplicationToken.Stub appToken; // window manager token
    final ActivityInfo info; // all about me
    final ApplicationInfo appInfo; // information about activity's app
    final int launchedFromUid; // always the uid who started the activity.
    final String launchedFromPackage; // always the package who started the activity.
    final int userId;          // Which user is this running for?
    final Intent intent;    // the original intent that generated us
    final ComponentName realActivity;  // the intent component, or target of an alias.
    final String shortComponentName; // the short component name of the intent
    final String resolvedType; // as per original caller;
    final String packageName; // the package implementing intent's component
    final String processName; // process where this component wants to run
    final String taskAffinity; // as per ActivityInfo.taskAffinity

7.ActivityStack管理当前系统所有Activity和状态

主要的几个变量,mTaskHistory记录着历史的activity,mLRUActivities记录的activity是根据LRU排序的,mPausingActivity切换activity时,正在暂停的activity。其源码如下

    //...
   private ArrayList<TaskRecord> mTaskHistory = new ArrayList<TaskRecord>();

   final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>();

   final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();

   ActivityRecord mPausingActivity = null;

   ActivityRecord mLastPausedActivity = null;

   ActivityRecord mLastNoHistoryActivity = null;

   ActivityRecord mResumedActivity = null;

   ActivityRecord mLastStartedActivity = null;
   //...

8.ActiveServices管理当前系统所有Service和状态

ActiveServices有一些常量规定Services执行的超时时间,一些list用记录各种状态的Service。
其部分源码如下

public final class ActiveServices {
    //...

    // How long we wait for a service to finish executing.
    static final int SERVICE_TIMEOUT = 20*1000;

    // How long we wait for a service to finish executing.
    static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
    //...

    final SparseArray<ServiceMap> mServiceMap = new SparseArray<ServiceMap>();

    /** * All currently bound service connections. Keys are the IBinder of * the client's IServiceConnection. */
    final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
            = new ArrayMap<IBinder, ArrayList<ConnectionRecord>>();

    /** * List of services that we have been asked to start, * but haven't yet been able to. It is used to hold start requests * while waiting for their corresponding application thread to get * going. */
    final ArrayList<ServiceRecord> mPendingServices
            = new ArrayList<ServiceRecord>();

    /** * List of services that are scheduled to restart following a crash. */
    final ArrayList<ServiceRecord> mRestartingServices
            = new ArrayList<ServiceRecord>();

    /** * List of services that are in the process of being destroyed. */
    final ArrayList<ServiceRecord> mDestroyingServices
            = new ArrayList<ServiceRecord>();

    static final class DelayingProcess extends ArrayList<ServiceRecord> {
        long timeoout;
    }

9.管理当前系统所有BroadCastReceiver和状态

AMS中保存着系统BroadCastReceiver,管理着广播接收器的调度和运行的超时时间等,其关键源码如下

    // How long we allow a receiver to run before giving up on it.
    static final int BROADCAST_FG_TIMEOUT = 10*1000;
    static final int BROADCAST_BG_TIMEOUT = 60*1000;

    /** * Keeps track of all IIntentReceivers that have been registered for * broadcasts. Hash keys are the receiver IBinder, hash value is * a ReceiverList. */
    final HashMap<IBinder, ReceiverList> mRegisteredReceivers =
            new HashMap<IBinder, ReceiverList>();

    BroadcastQueue mFgBroadcastQueue;
    BroadcastQueue mBgBroadcastQueue;
    // Convenient for easy iteration over the queues. Foreground is first
    // so that dispatch of foreground broadcasts gets precedence.
    final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
    原文作者:吴镇佳
    原文地址: https://blog.csdn.net/qq526459753/article/details/51034637
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞