AMS启动流程

本文均采用Android 14代码进行讲解,学习可以使用以下地址:Search

一、AMS启动流程

AMS的启动是在SyetemServer进程中启动的,从SyetemServer的main方法开始进入:

1.SystemServer.java

main(String[] args)

/**
 * The main entry point from zygote.
 */
public static void main(String[] args) {
    new SystemServer().run();
}

main方法中只调用了SystemServer的run方法,如下所示。

run()

从下面的注释中可以看到,官方把系统服务分为了三种类型,分别是引导服务、核心服务和其他服务,其中其他服务是一些非紧要和一些不需要立即启动的服务。系统服务总共大约有80多个,我们主要来查看引导服务AMS是如何启动的。

private void run() {
      		 // Initialize native services.
         	//1.加载了动态库libandroid_servers.so
           System.loadLibrary("android_servers");
       ......
	         // Create the system service manager.
        	 //2.创建SystemServiceManager,它会对系统的服务进行创建、启动和生命周期管理。
	         mSystemServiceManager = new SystemServiceManager(mSystemContext);
	         mSystemServiceManager.setStartInfo(mRuntimeRestart,
	                 mRuntimeStartElapsedTime, mRuntimeStartUptime);
	         mDumper.addDumpable(mSystemServiceManager);
	     ......   
			    	// Start services.
        try {
           t.traceBegin("StartServices");
           //用SystemServiceManager启动了ActivityManagerService、PowerManagerService、PackageManagerService等服务。
			 		 startBootstrapServices(t);
           //启动了BatteryService、UsageStatsService和WebViewUpdateService。
           startCoreServices(t);
        	 //启动了CameraService、AlarmManagerService、VrManagerService等服务。这些服务的父类均为SystemService。
           startOtherServices(t);
        	 startApexServices(t);
           // Only update the timeout after starting all the services so that we use
           // the default timeout to start system server.
           updateWatchdogTimeout(t);
       } catch (Throwable ex) {
           Slog.e("System", "******************************************");
           Slog.e("System", "************ Failure starting system services", ex);
           throw ex;
       } finally {
           t.traceEnd(); // StartServices
       }
       ...
   }

startBootstrapServices(@NonNull TimingsTraceAndSlog t)

调用了ActivityManagerService.Lifecycle.startService方法

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
    t.traceBegin("startBootstrapServices");
  	//尽早启动watchdog,这样我们就可以使系统服务器崩溃
    // 如果我们在早期启动时死锁
    t.traceBegin("StartWatchdog");
    final Watchdog watchdog = Watchdog.getInstance();
    watchdog.start();
    mDumper.addDumpable(watchdog);	
    .....
    // Activity manager runs the show.
    t.traceBegin("StartActivityManager");
    // TODO: Might need to move after migration to WM.
    ActivityTaskManagerService atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();
    //调用了ActivityManagerService.Lifecycle.startService方法,跟进代码看最终调用哪个方法
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
            mSystemServiceManager, atm);
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    mWindowManagerGlobalLock = atm.getGlobalLock();
    t.traceEnd();
......

2.ActivityManagerService.java

Lifecycle.startService(SystemServiceManager ssm,ActivityTaskManagerService atm)

最终调用SystemServiceManager的startService方法,参数就是ActivityManagerService.Lifecycle.class,继续跟进SystemServiceManager,最终调用Lifecycle的getService方法,这个方法会返回AMS类型的mService对象,这样AMS实例就会被创建并且返回。

//Lifecycle继承自SystemService
public static final class Lifecycle extends SystemService {
	  public Lifecycle(Context context) {
	      super(context);
      	//当通过反射来创建Lifecycle实例时,会调用此方法创建AMS实例
	      mService = new ActivityManagerService(context, sAtm);
	  }
    public static ActivityManagerService startService(
            SystemServiceManager ssm, ActivityTaskManagerService atm) {
        sAtm = atm;
      	//调用SystemServiceManager的startService方法,参数就是ActivityManagerService.Lifecycle.class,最终调用Lifecycle的getService方法,这个方法会返回AMS类型的mService对象,这样AMS实例就会被创建并且返回。
        return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
				@Override
		public void onStart(){
				Service.start;
		}
  	...
  	//这个方法会返回AMS类型的mService对象,这样AMS实例就会被创建并且返回。
     public ActivityManagerService getService() {
         return mService;
     }
}

3.SystemServiceManager.java

startService(Class serviceClass)

首先会获取传进来的Lifecycle的构造器constructor,然后调用constructor的newInstance方法来创建Lifecycle类型的service对象,调用重载的startService,最后返回service

public  T startService(Class serviceClass) {
    try {
        final String name = serviceClass.getName();
        Slog.i(TAG, "Starting " + name);
        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

        // Create the service.
        if (!SystemService.class.isAssignableFrom(serviceClass)) {
            throw new RuntimeException("Failed to create " + name
                    + ": service must extend " + SystemService.class.getName());
        }
        final T service;
        try {
        	  //1.获取传进来的Lifecycle的构造器constructor
            Constructor constructor = serviceClass.getConstructor(Context.class);
            //调用constructor的newInstance方法来创建Lifecycle类型的service对象
						service = constructor.newInstance(mContext);
        } catch (InstantiationException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service could not be instantiated", ex);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service must have a public constructor with a Context argument", ex);
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service must have a public constructor with a Context argument", ex);
        } catch (InvocationTargetException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service constructor threw an exception", ex);
        }
      	//调用重载的startService
        startService(service);
      	//返回service
        return service;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
}

startService(@NonNull final SystemService service)

首先会将上面创建的service添加到ArrayList类型的mServices对象中来完成注册,然后调用service的onStart方法来启动service

public void startService(@NonNull final SystemService service) {
    // Check if already started
    String className = service.getClass().getName();
    if (mServiceClassnames.contains(className)) {
        Slog.i(TAG, "Not starting an already started service " + className);
        return;
    }
    mServiceClassnames.add(className);

    //1.将上面创建的service添加到ArrayList类型的mServices对象中来完成注册
    mServices.add(service);

    // Start it.
    long time = SystemClock.elapsedRealtime();
    try {
      	//2.调用service的onStart方法来启动service
        service.onStart();
    } catch (RuntimeException ex) {
        throw new RuntimeException("Failed to start service " + service.getClass().getName()
                + ": onStart threw an exception", ex);
    }
    warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

4.流程总结:

总的流程主要涉及SystemServer、ActivityManagerService、SystemServiceManager三个类,SystemServer的run方法会调用去启动引导服务startBootstrapServices,其中AMS也在里面,startBootstrapServices调用了startService方法,跟进代码看最终调用SystemServiceManager里面的startService,中间会有一系列的调用,但最后会通过Lifecycle创建AMS实例,然后通过Lifecycle里面的getService(),这个方法会返回AMS类型的mService对象。

二、

三、Activity的启动流程

Activity的启动流程,Android 7使用了代理模式的方式通讯,Android8.0开始使用了aidl的方式进行通信,这里以Android13和Android的代码流程为例。

Android13

Android 7

ActivityManager是一个和AMS相关联的类,它主要对运行中的Activity进行管理,这些管理工作并不是由ActivityManager来处理的,而是交由AMS来处理,ActivityManager中的方法会通过ActivityManagerNative(以后简称AMN)的getDefault方法来得到ActivityManagerProxy(以后简称AMP),通过AMP就可以和AMN进行通信,而AMN是一个抽象类,它会将功能交由它的子类AMS来处理,因此,AMP就是AMS的代理类。AMS作为系统核心服务,很多API是不会暴露给ActivityManager的,因此 并不算是AMS家族一份子。

为了讲解AMS家族,这里拿Activity的启动过程举例,Activity的启动过程中会调用Instrumentation的execStartActivity方法,如下所示。

frameworks/base/core/java/android/app/Instrumentation.java

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
      ...
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

execStartActivity方法中会调用AMN的getDefault来获取AMS的代理类AMP。接着调用了AMP的startActivity方法,先来查看AMN的getDefault方法做了什么,如下所示。

frameworks/base/core/java/android/app/ActivityManagerNative.java

 static public IActivityManager getDefault() {
        return gDefault.get();
    }
    private static final Singleton gDefault = new Singleton() {
        protected IActivityManager create() {
            IBinder b = ServiceManager.getService("activity");//1
            if (false) {
                Log.v("ActivityManager", "default service binder = " + b);
            }
            IActivityManager am = asInterface(b);//2
            if (false) {
                Log.v("ActivityManager", "default service = " + am);
            }
            return am;
        }+
    };
}

getDefault方法调用了gDefault的get方法,我们接着往下看,gDefault 是一个Singleton类。注释1处得到名为”activity”的Service引用,也就是IBinder类型的AMS的引用。接着在注释2处将它封装成AMP类型对象,并将它保存到gDefault中,此后调用AMN的getDefault方法就会直接获得AMS的代理对象AMP。注释2处的asInterface方法如下所示。

frameworks/base/core/java/android/app/ActivityManagerNative.java

static public IActivityManager asInterface(IBinder obj) {
    if (obj == null) {
        return null;
    }
    IActivityManager in =
        (IActivityManager)obj.queryLocalInterface(descriptor);
    if (in != null) {
        return in;
    }
    return new ActivityManagerProxy(obj);
}

asInterface方法的主要作用就是将IBinder类型的AMS引用封装成AMP,AMP的构造方法如下所示。

frameworks/base/core/java/android/app/ActivityManagerNative.java

class ActivityManagerProxy implements IActivityManager
{
    public ActivityManagerProxy(IBinder remote)
    {
        mRemote = remote;
    }
...
 }

AMP的构造方法中将AMS的引用赋值给变量mRemote ,这样在AMP中就可以使用AMS了。

其中IActivityManager是一个接口,AMN和AMP都实现了这个接口,用于实现代理模式和Binder通信。

再回到Instrumentation的execStartActivity方法,来查看AMP的startActivity方法,AMP是AMN的内部类,代码如下所示。

frameworks/base/core/java/android/app/ActivityManagerNative.java

public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
           String resolvedType, IBinder resultTo, String resultWho, int requestCode,
           int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
     ...
       data.writeInt(requestCode);
       data.writeInt(startFlags);
     ...
       mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);//1
       reply.readException();+
       int result = reply.readInt();
       reply.recycle();
       data.recycle();
       return result;
   }

首先会将传入的参数写入到Parcel类型的data中。在注释1处,通过IBinder类型对象mRemote(AMS的引用)向服务端的AMS发送一个START_ACTIVITY_TRANSACTION类型的进程间通信请求。那么服务端AMS就会从Binder线程池中读取我们客户端发来的数据,最终会调用AMN的onTransact方法,如下所示。

frameworks/base/core/java/android/app/ActivityManagerNative.java

   @Override
   public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
           throws RemoteException {
       switch (code) {
       case START_ACTIVITY_TRANSACTION:
       {
       ...
           int result = startActivity(app, callingPackage, intent, resolvedType,
                   resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
           reply.writeNoException();
           reply.writeInt(result);
           return true;
       }
   }

onTransact中会调用AMS的startActivity方法,如下所示。
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

 @Override
 public final int startActivity(IApplicationThread caller, String callingPackage,
         Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
         int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
     return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
             resultWho, requestCode, startFlags, profilerInfo, bOptions,
             UserHandle.getCallingUserId());
 }

startActivity方法会最后return startActivityAsUser方法,如下所示。
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

 @Override
 public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
         Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
         int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
     enforceNotIsolatedCaller("startActivity");
     userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
             userId, false, ALLOW_FULL_ONLY, "startActivity", null);
     return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
             resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
             profilerInfo, null, null, bOptions, false, userId, null, null);
  }           

startActivityAsUser方法最后会return ActivityStarter的startActivityMayWait方法,这一调用过程已经脱离了本节要讲的AMS家族。

在Activity的启动过程中提到了AMP、AMN和AMS,它们共同组成了AMS家族的主要部分,如下图所示。

AMS启动流程_第1张图片

AMP是AMN的内部类,它们都实现了IActivityManager接口,这样它们就可以实现代理模式,具体来讲是远程代理:AMP和AMN是运行在两个进程的,AMP是Client端,AMN则是Server端,而Server端中具体的功能都是由AMN的子类AMS来实现的,因此,AMP就是AMS在Client端的代理类。AMN又实现了Binder类,这样AMP可以和AMS就可以通过Binder来进行进程间通信。

AMS启动流程_第2张图片

Android解析ActivityManagerService(一)AMS启动流程和AMS家族_android 解析 activitymanagersservice 刘望舒-CSDN博客

android api 26 ActivityManagerNative类被弃用。代理类ActivityManagerProxy已经被删除。改用AIDL方式。_notewakeupalarm-CSDN博客

framework | Activity启动流程(android-31) - 掘金

面试必备:Android(9.0)Activity启动流程(一) - 知乎

http://androidxref.com/7.1.2_r36/

Search

你可能感兴趣的:(Framework)