欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

详解Android Activity的启动流程

程序员文章站 2022-04-05 14:22:25
前言activity启动的流程分为两部分:一是在activity中通过startactivity(intent intent)方法启动一个activity;二是我们在桌面通过点击应用图标启动一个app...

前言

activity启动的流程分为两部分:一是在activity中通过startactivity(intent intent)方法启动一个activity;二是我们在桌面通过点击应用图标启动一个app然后显示activity;第二种方式相较于第一种方式更加全面,所以本文会以第二种流程来分析。

简要

我们手机的桌面是一个叫做launcher的activity,它罗列了手机中的应用图标,图标中包含安装apk时解析的应用默认启动页等信息。在点击应用图标时,即将要启动的app和launcher、ams、zygote所属进程不同所以涉及到launcher与ams,ams与zygote,ams与新app这四者多次通信,才会启动一个app,然后再启动activity,整体的时序图如下:

详解Android Activity的启动流程

接下来根据源码来梳理一下流程。

1.launcher向ams发送启动activity

launcher本身是一个activity,在用户点击应用图标时,调用startactivitysafely方法,最后调用到activity.startactivity(),函数调用如下

launcher.java
 public boolean startactivitysafely(view v, intent intent, iteminfo item) {
  ...
  //标记在新的栈启动
  intent.addflags(intent.flag_activity_new_task);
  ...
  startactivity(intent, optsbundle);
  ...
 }

activity.java
 @override
 public void startactivity(intent intent) {
  this.startactivity(intent, null);
 }

 @override
 public void startactivity(intent intent, @nullable bundle options) {
  ...
  if (options != null) {
   //-1为requestcode表明不需要知道是否启动成功
   startactivityforresult(intent, -1, options);
  } else {
   startactivityforresult(intent, -1);
  }
 }

 public void startactivityforresult(@requirespermission intent intent, int requestcode,
   @nullable bundle options) {
   ...
   instrumentation.activityresult ar =
    minstrumentation.execstartactivity(
     this, mmainthread.getapplicationthread(), mtoken,this,intent, requestcode, options);
   ...
 }

每个activity都持有instrumentation对象,通过它的execstartactivity函数来继续完成启动activity的流程,这个函数中传入了mmainthread.getapplicationthread(),它获取到的是activitythread的内部类applicationthread,这是一个binder对象,之后ams通过此对象与app的通信。

instrumentation.java
public activityresult execstartactivity(
   context who, ibinder contextthread, ibinder token, activity target,
   intent intent, int requestcode, bundle options) {
 ...
	int result = activitytaskmanager.getservice().startactivity(whothread,who.getbasepackagename(),
  who.getattributiontag(),intent,intent.resolvetypeifneeded(who.getcontentresolver()),
  token,target != null ? target.membeddedid : null, requestcode, 0, null, options); 
 ...
}

activitytaskmanager.java
public static iactivitytaskmanager getservice() {
  return iactivitytaskmanagersingleton.get();
}
 
private static final singleton<iactivitytaskmanager> iactivitytaskmanagersingleton =
   new singleton<iactivitytaskmanager>() {
    @override
    protected iactivitytaskmanager create() {
     final ibinder b = servicemanager.getservice(context.activity_task_service);
     return iactivitytaskmanager.stub.asinterface(b);
    }
    }
};

这一步launcher开始向ams通信,由于在不同的进程所以需要通过binder来通信,iactivitytaskmanager是一个代理ams端binder的对象,之后ams开始startactivity。 到这里launcher向ams请求启动一个activity的流程就结束了。

2.ams启动activity并通知launcher进入paused状态

现在的流程是在ams中,也就是另一个进程中,上一步通过代理调用到ams的startactivity方法,接下来的调用如下:

activitytaskmanagerservice.java
 @override
 public final int startactivity(iapplicationthread caller, string callingpackage,
   string callingfeatureid, intent intent, string resolvedtype, ibinder resultto,
   string resultwho, int requestcode, int startflags, profilerinfo profilerinfo,
   bundle boptions) {
  return startactivityasuser(caller, callingpackage, callingfeatureid, intent, resolvedtype,
    resultto, resultwho, requestcode, startflags, profilerinfo, boptions,
    userhandle.getcallinguserid());
 }
 
 @override
 public int startactivityasuser(iapplicationthread caller, string callingpackage,
   string callingfeatureid, intent intent, string resolvedtype, ibinder resultto,
   string resultwho, int requestcode, int startflags, profilerinfo profilerinfo,
   bundle boptions, int userid) {
  return startactivityasuser(caller, callingpackage, callingfeatureid, intent, resolvedtype,
    resultto, resultwho, requestcode, startflags, profilerinfo, boptions, userid,
    true /*validateincominguser*/);
 }
 
 private int startactivityasuser(iapplicationthread caller, string callingpackage,
   @nullable string callingfeatureid, intent intent, string resolvedtype,
   ibinder resultto, string resultwho, int requestcode, int startflags,
   profilerinfo profilerinfo, bundle boptions, int userid, boolean validateincominguser) {
	 ...
  userid = getactivitystartcontroller().checktargetuser(userid, validateincominguser,
    binder.getcallingpid(), binder.getcallinguid(), "startactivityasuser");
    
  return getactivitystartcontroller().obtainstarter(intent, "startactivityasuser")
    .setcaller(caller)
    .setcallingpackage(callingpackage)
    .setcallingfeatureid(callingfeatureid)
    .setresolvedtype(resolvedtype)
    .setresultto(resultto)
    .setresultwho(resultwho)
    .setrequestcode(requestcode)
    .setstartflags(startflags)
    .setprofilerinfo(profilerinfo)
    .setactivityoptions(boptions)
    .setuserid(userid)
    .execute();
 }
 
 activitystarter obtainstarter(intent intent, string reason) {
  return mfactory.obtain().setintent(intent).setreason(reason);
 }

上面几步主要是做权限检查

activitystarter.java
 int execute() {
 ...
 res = executerequest(mrequest);
 ...
 }
//层层调用会到下面这个方法
activitystack.java
 private boolean resumetopactivityinnerlocked(activityrecord prev, activityoptions options) {
 ...
 if (mresumedactivity != null) {
  pausing |= startpausinglocked(userleaving, false , next);
 }
 ...
 mstacksupervisor.startspecificactivity(next, true, false);
 ...
 }

startpausinglocked方法主要是通知launcher进入paused状态,在它进入这个状态后,在activitystacksupervisor.startspecificactivity方法判断新的app进程状态做出不同响应,如下:

activitystacksupervisor.java
void startspecificactivity(activityrecord r, boolean andresume, boolean checkconfig) {
  // 获取要启动的activity进程信息
  final windowprocesscontroller wpc =
    mservice.getprocesscontroller(r.processname, r.info.applicationinfo.uid);
  boolean knowntobedead = false;
  //如果进程存在且有进程中有线程存在 就是启动一个同应用的activity(普通activity就在此执行)
  if (wpc != null && wpc.hasthread()) {
   try {
    realstartactivitylocked(r, wpc, andresume, checkconfig);
    return;
   } catch (remoteexception e) {
    slog.w(tag, "exception when starting activity "
      + r.intent.getcomponent().flattentoshortstring(), e);
   }

   // if a dead object exception was thrown -- fall through to
   // restart the application.
   knowntobedead = true;
  }
	//否则通过ams向zygote进程请求创建新的进程
  r.notifyunknownvisibilitylaunchedforkeyguardtransition();
  final boolean istop = andresume && r.istoprunningactivity();
  mservice.startprocessasync(r, knowntobedead, istop, istop ? "top-activity" : "activity");
}

截止到这里完成了launcher和ams的通信,以及ams和zygote进程的通信,接下来我们要创建要启动的app的线程,即activitythread。

3.新的进程启动,activitythread的main函数入口

上一部分zygote启动新的进程时标记activitythread.main函数,在zygote创建好新进程后通过反射调用此方法,现在处于新app的进程中。

activitythread.java
 public static void main(string[] args) {
  ...
  looper.preparemainlooper();
	...
  activitythread thread = new activitythread();
  thread.attach(false, startseq);
	...
  looper.loop();
	...
 }
 
 private void attach(boolean system, long startseq) {
   final iactivitymanager mgr = activitymanager.getservice();
   try {
    mgr.attachapplication(mappthread, startseq);
   } catch (remoteexception ex) {
    throw ex.rethrowfromsystemserver();
   }
   ...
 }
activitymanagerservice.java
 private boolean attachapplicationlocked(@nonnull iapplicationthread thread,
   int pid, int callinguid, long startseq) {
   ...
   thread.bindapplication(processname, appinfo, providerlist,
      instr2.mclass,
      profilerinfo, instr2.marguments,
      instr2.mwatcher,
      instr2.muiautomationconnection, testmode,
      mbindertransactiontrackingenabled, enabletrackallocation,
      isrestrictedbackupmode || !normalmode, app.ispersistent(),
      new configuration(app.getwindowprocesscontroller().getconfiguration()),
      app.compat, getcommonserviceslocked(app.isolated),
      mcoresettingsobserver.getcoresettingslocked(),
      buildserial, autofilloptions, contentcaptureoptions,
      app.mdisabledcompatchanges);
    ...
    didsomething = matminternal.attachapplication(app.getwindowprocesscontroller());
    ...
 }

这里主要是创建了looper和activitythread对象,然后将当前应用applicationthread注册到ams中,applicationthread是activitythread的内部类实现了iapplicationthread.stub用此对象可跨进程通信,上面的代码逻辑分两步,第一步,在ams绑定applicationthread时,发送了一个h.bind_application的message,在handler中处理该消息时调用了application的oncreate方法,第二步,在matminternal的attachapplication层层调用到activitystacksupervisor.realstartactivitylocked方法,整体如下:

public final void bindapplication(string processname, applicationinfo appinfo,
    providerinfolist providerlist, componentname instrumentationname,
    profilerinfo profilerinfo, bundle instrumentationargs,
    iinstrumentationwatcher instrumentationwatcher,
    iuiautomationconnection instrumentationuiconnection, int debugmode,
    boolean enablebindertracking, boolean trackallocation,
    boolean isrestrictedbackupmode, boolean persistent, configuration config,
    compatibilityinfo compatinfo, map services, bundle coresettings,
    string buildserial, autofilloptions autofilloptions,
    contentcaptureoptions contentcaptureoptions, long[] disabledcompatchanges) {
    	...
    	sendmessage(h.bind_application, data);
 }
    
public void handlemessage(message msg) {
 switch (msg.what) {
  case bind_application:
  	appbinddata data = (appbinddata)msg.obj;
  	handlebindapplication(data);
  	trace.traceend(trace.trace_tag_activity_manager);
  	break;
  ...
  }
}

private void handlebindapplication(appbinddata data) {
	...
	minstrumentation.callapplicationoncreate(app);
	...
}

到这里为止,新的app线程已经启动并且绑定了application。

4.创建activity

activitystacksupervisor.java
boolean realstartactivitylocked(activityrecord r, windowprocesscontroller proc,
  boolean andresume, boolean checkconfig) throws remoteexception {
  ...
  final clienttransaction clienttransaction = clienttransaction.obtain(
    proc.getthread(), r.apptoken);
   final displaycontent dc = r.getdisplay().mdisplaycontent;
   clienttransaction.addcallback(launchactivityitem.obtain(new intent(r.intent),
     system.identityhashcode(r), r.info,
     mergedconfiguration.getglobalconfiguration(),
     mergedconfiguration.getoverrideconfiguration(), r.compat,
     r.launchedfrompackage, task.voiceinteractor, proc.getreportedprocstate(),
     r.getsavedstate(), r.getpersistentsavedstate(), results, newintents,
     dc.isnexttransitionforward(), proc.createprofilerinfoifneeded(),
     r.assisttoken, r.createfixedrotationadjustmentsifneeded()));

   final activitylifecycleitem lifecycleitem;
   if (andresume) {
    lifecycleitem = resumeactivityitem.obtain(dc.isnexttransitionforward());
   } else {
    lifecycleitem = pauseactivityitem.obtain();
   }
   clienttransaction.setlifecyclestaterequest(lifecycleitem);
   //执行clienttransaction
   mservice.getlifecyclemanager().scheduletransaction(clienttransaction);
   ...
}

clienttransaction管理了activity的启动信息,由clientlifecyclemanager执行,scheduletransaction方法中发送了execute_transaction的消息给activitythread的h类处理,然后执行transactionexecutor.execute(),之后执行handlelaunchactivity方法,如下

 void scheduletransaction(clienttransaction transaction) throws remoteexception {
  final iapplicationthread client = transaction.getclient();
  transaction.schedule();
  ...
 }

 public void schedule() throws remoteexception {
  mclient.scheduletransaction(this);
 }

 void scheduletransaction(clienttransaction transaction) {
  transaction.preexecute(this);
  sendmessage(activitythread.h.execute_transaction, transaction);
 }

 class h extends handler {
   ...
   public void handlemessage(message msg) {
   ...
   case execute_transaction:
    final clienttransaction transaction = (clienttransaction) msg.obj;
    mtransactionexecutor.execute(transaction);
    if (issystem()) {
     transaction.recycle();
    }
    break;
   ...
   } 
   ...
 }

 public void execute(clienttransactionhandler client, ibinder token,
   pendingtransactionactions pendingactions) {
  ...
  client.handlelaunchactivity(r, pendingactions, null /* customintent */);
 }

接下来由activitythread来处理后续操作

public activity handlelaunchactivity(activityclientrecord r,
   pendingtransactionactions pendingactions, intent customintent) {
  ...
  final activity a = performlaunchactivity(r, customintent);
  ...
  return a;
}

private activity performlaunchactivity(activityclientrecord r, intent customintent) {
  contextimpl appcontext = createbasecontextforactivity(r);
  ...
  java.lang.classloader cl = appcontext.getclassloader();
  activity = minstrumentation.newactivity(cl, component.getclassname(), r.intent);
  ...
  application app = r.packageinfo.makeapplication(false, minstrumentation);
  ...
  activity.attach(appcontext, this, getinstrumentation(), r.token,
      r.ident, app, r.intent, r.activityinfo, title, r.parent,
      r.embeddedid, r.lastnonconfigurationinstances, config,
      r.referrer, r.voiceinteractor, window, r.configcallback,
      r.assisttoken);
  ...
  activity.settheme(theme);
  ...
  minstrumentation.callactivityoncreate(activity, r.state, r.persistentstate);
}

performlaunchactivity方法中主要做了以下几件事:

  1. 创建要启动activity的上下文环境
  2. 通过instrumentation的newactivity方法,以反射形式创建activity实例
  3. 如果application不存在的话会创建application并调用application的oncreate方法
  4. 初始化activity,创建window对象(phonewindow)并实现activity和window相关联
  5. 通过instrumentation调用activity的oncreate方法

总结

根activity整体上学习意义较大,建议从整体流程入手,遇到流程不通时也可以debug。 activity的整体启动流程:

  1. 点击图标,launcher向ams请求启动该app
  2. ams反馈收到启动请求,并告知launcher进入pause状态
  3. launcher进入paused状态并告知ams
  4. ams检测新的app是否已启动,否则通知zygote创建新的进程并启动activitythread.main()
  5. 应用进程启动activitythread
  6. activitythread中h处理需要启动activity的请求消息

以上就是详解android activity的启动流程的详细内容,更多关于android activity的启动流程的资料请关注其它相关文章!