AMS-总结

深入理解Android内核设计思想 至AMS总结

AMS

ActivityManagerService(AMS)是Android提供的一个用于管理Activity(和其他组件)运行状态的系统进程。

AMS寄存在systemServer中,它在系统启动的时候,创建一个现场来循环处理客户的请求

AMS启动

SystemServer是Android系统的一个核心进程,它是由zygote进程创建的,因此在android的启动过程中位于zygote之后。查看SystemServer 中的main方法(以SDK19位例子)
SystemServer

 public static void main(String[] args) {
        。。。。。。
        ServerThread thr = new ServerThread();
        thr.initAndLoop();
    }
}
initAndLoop{
 。。。。。。。
  context = ActivityManagerService.main(factoryTest);//启动AMS
  。。。。。。
  ActivityManagerService.setSystemProcess();//向ServiceManager 注册
}

AMS

 public static final Context main(int factoryTest) {
        //创建AMS线程
        AThread thr = new AThread();
        thr.start();
        synchronized (thr) {
            while (thr.mService == null) {
                try {
                   //对于SystemServer所在的现场,必须等到AThread成功启动后才能继续执行下去 
                    thr.wait();
                } catch (InterruptedException e) {
                }
            }
        }

        ActivityManagerService m = thr.mService;
        mSelf = m;
        。。。。。
        //ActivityStackSupervisor 是用来管理ActivityStack,ActivityStack是管理当前系统中所有Activity状态的一个数据结构
        m.mStackSupervisor = new ActivityStackSupervisor(m, context, thr.mLooper);
    }

AThread

   @Override
   public void run() {
     Looper.prepare();
        synchronized (this) {
             mService = m;
             mLooper = Looper.myLooper();
              //会唤醒所有在thr这个等待队列的目标,原因在于如果SystemServer后续的运行需要依赖AMS,所以如果AMS为就绪,贸然返回会有问题
             notifyAll();
         }
        Looper.loop();
  }

Activity Stack

ActivityStackSupervisor在AMS启动的时候就创建了,管理ActivityStack。
ActivityState,用来描述Activity所可能经历的所有状态,

    enum ActivityState {
        INITIALIZING,//初始化
        RESUMED,//回复
        PAUSING,//正在暂停
        PAUSED,//已经暂停
        STOPPING,//正在停止
        STOPPED,//已经停止
        FINISHING,//已经完成
        DESTROYING,//正在销毁
        DESTROYED//以及销毁
    }

在ActivityStackSupervisor中

 //mStacks存储了所有的stack
 private ArrayList<ActivityStack> mStacks = new ArrayList<ActivityStack>();
  //mHomeStack存储luncher相关的内容,也就是home,另一个存储当前处于焦点的stack,mHomeStack会在开机之后自动加入到mStacks中去,而且只占据第0号位置,mFocusedStack占据第1号位置,
 private ActivityStack mFocusedStack;
 private ActivityStack mHomeStack;


void setWindowManager(WindowManagerService wm) {  
    mWindowManager = wm;  
    mHomeStack = new ActivityStack(mService, mContext, mLooper, HOME_STACK_ID);//初始化home 
    mStacks.add(mHomeStack);  
}  

startActivity的流程

  1. startActivity
  2. startActivityAsUser
  3. startActivityMayWait
  4. startActivityLocked
  5. startActivityUncheckedLocked
    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, options,
            UserHandle.getCallingUserId());
    }
   //做权限检查
    @Override
    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
            //检查调用调用者是否被隔离的对象
        enforceNotIsolatedCaller("startActivity");
       // 调用者是否有权利执行这个操作
        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
                false, ALLOW_FULL_ONLY, "startActivity", null);
        return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, options, false, userId, null, null);
    }

在startActivityMayWait方法做的步骤


    final int startActivityMayWait(....) {
     //.....
     //如果PackageManager,来查找
     ActivityInfo aInfo =
                resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);
     //.....
    //判断当前系统以及存在重量级进程,不是即将要启动这个,那么就要给intent的赋值
    if(mService.mHeavyWeightProcess != null &&(mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid||....)){
      //...
    Intent newIntent = new Intent();
    if (requestCode >= 0) {
    newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
    }
    newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,new IntentSender(target));
    //....
    //调用startActivityLocked来执行启动工作
    int res =startActivityLocked(.....);
  }
 }

startActivityLocked 主要任务是为了确保调用者在本身的进程中是存在的,检查flag

//FLAG_ACTIVITY_FORWARD_RESULT 这个是多界面传数值 A->B->C c可以直接返回给A,下面这段代码将b接受到的result目标对象设置为A
  if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
            if (requestCode >= 0) {
                ActivityOptions.abort(options);
                return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
            }
            resultRecord = sourceRecord.resultTo;
            if (resultRecord != null && !resultRecord.isInStackLocked()) {
                resultRecord = null;
            }
            resultWho = sourceRecord.resultWho;
            requestCode = sourceRecord.requestCode;
            sourceRecord.resultTo = null;
            if (resultRecord != null) {
                resultRecord.removeResultsLocked(sourceRecord, resultWho, requestCode);
            }
            if (sourceRecord.launchedFromUid == callingUid) {
                callingPackage = sourceRecord.launchedFromPackage;
            }
        }

        //.....
       //查找目标的Activity 如果没找到或者,这个目标的ActivityInfo是空的,就报错退出
       //...
       //检查调用者是否有权限来启动这个Activity
       final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid, callingUid);
       abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,callingPid, resolvedType, aInfo.applicationInfo);

//最后生成一个ActivityRecord 变量r,记录当前的各项判断结果
 ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
                intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
                requestCode, componentSpecified, voiceSession != null, this, container, options);
          //.....
startActivityUncheckedLocked();     

startActivityUncheckedLocked 根据intent的启动标志和启动模式,处理task中是否启动等相应的逻辑

  1. 获取启动标志
  2. 处理FLAG_ACTIVITY_NO_USER_ACTION.这个标志表示并不是用户主观意识启动的,如来电,闹钟等时间
  3. START_FLAG_ONLY_IF_NEEDED 确认过启动这和调用者是同一个,就不会重复操作
  4. 判断是否启动一个新的task
  5. 最后调用realStartActivityLocked,是真正执行启动操作。
 ...
  //系统参数发送变化,通知Activity
  if (checkConfig) {
    Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(mService.mConfiguration,
        r.mayFreezeScreenLocked(app) ? r.appToken : null);
    mService.updateConfigurationLocked(config, r, false, false);
  }
  //将进程描述符设置到启动的Activity描述符中
  r.app = app;
  app.waitingToKill = null;
  //将启动的Activity添加到进程启动的Activity列表中
  int idx = app.activities.indexOf(r);
  if (idx < 0) {
    app.activities.add(r);
  }

FLAG

http://www.cnblogs.com/xingfuzzhd/archive/2012/12/26/2834078.html

//参考文章

http://blog.csdn.net/xueerfei008/article/details/23171677
http://www.2cto.com/kf/201408/325323.html
http://blog.csdn.net/yueliangniao1/article/details/7227165
深入理解Android内核设计思想

    原文作者:林胖子的私生活
    原文地址: https://blog.csdn.net/qq_22329521/article/details/52269650
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞