ActivityThead ActivityManagerService 和activity关系概述

Activity 是安卓中最重要的一个元素,安卓如果管理activity? 进程中的主线程如何建立?关于这几个问题我们将简要概述,不会展示太多的代码。

首先来看一下进程的入口函数:ActivityThead,从应用程序的角度,所有的activity 信息都保存在这个类的成员变量中

  1. final HashMap <IBinder, ActivityRecord> mActivities = new HashMap <IBinder, ActivityRecord> ();

   也就是mActivities 记录了所有的activity 实例,这些实例都是这个进程创建的。 Activity Thread 如何创建应用?在这个类的main函数中,它会启动应用和创建消息循环。如下:

    

  1. /***  . ??*/public static final void main(String[] args) {  SamplingProfilerIntegration.start();  Process.setArgV0("<pre-initialized>");  Looper.prepareMainLooper();  ActivityThread thread = new ActivityThread();  thread.attach(false);  Looper.loop();    if (Process.supportsProcesses()) {     throw new RuntimeException("Main thread loop unexpectedly exited");   }   thread.detach();   String name = (thread.mInitialApplication != null)            ? thread.mInitialApplication.getPackageName()            : "<unknown>";Slog.i(TAG, "Main thread of " + name + " is now exiting");    }  

在消息循环创建之前,通过thread.attach (false) 初始化应用的runtime环境,并且通过mAppThread建立ActivityManagerService与应用之间的桥梁, mAppThread是一个是一个代理,不是一个线程,不要被它的名字迷惑。


  1. android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");            RuntimeInit.setApplicationObject(mAppThread.asBinder());            IActivityManager mgr = ActivityManagerNative.getDefault();            try {                mgr.attachApplication(mAppThread);            } catch (RemoteException ex) {            }  


注意:每个APP对应一个 ActivityThread实例,也就是ActivityThread.main, 每个实例也对应一个ApplicationThread对象,它是activityThread和ActivityManagerService的桥梁。Attach函数主要建立了这个桥梁

ActivityManagerService:

ActivityManagerService 主要实现了对 activity的管理: 历史堆栈里面,最上层是正在运行的Activity.当创建一个新的Acticity的,会创建一个记录r.

  1. HistoryRecord r = new HistoryRecord (this, callerApp, callingUid, intent, resolvedType, aInfo, mConfiguration, resultRecord, resultWho, requestCode, componentSpecified);

然后将r保存到堆栈中。

  1. mHistory.add (addPos, r);
但是关于activity 只保存在服务端的mHistory ,客户端没有关注这个activity的记录.我们需要 scheduleLaunchActivity方法创建一个新的。

  1. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,                ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,                List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {            ActivityRecord r = new ActivityRecord();            r.token = token;            r.ident = ident;            r.intent = intent;            r.activityInfo = info;            r.state = state;            r.pendingResults = pendingResults;            r.pendingIntents = pendingNewIntents;            r.startsNotResumed = notResumed;            r.isForward = isForward;            queueOrSendMessage(H.LAUNCH_ACTIVITY, r);        }  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值