Android Activity组件的启动过程
0、总图
1、总图中的第一步,Laucher主线程向ActivityManagerService进程发出START_ACTIVITY_TRANSACTION
如图:第一步
~/Android/frameworks/base/core/java/android/app
----ActivityManagerNative.java
class ActivityManagerProxy implements IActivityManager
{ public int startActivity(IApplicationThread caller, Intent intent,
String resolvedType, Uri[] grantedUriPermissions, int grantedMode,
IBinder resultTo, String resultWho,
int requestCode, boolean onlyIfNeeded,
boolean debug) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(caller != null ? caller.asBinder() : null);
intent.writeToParcel(data, 0);
.........
data.writeStrongBinder(resultTo);
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
}
当中caller为:
final ApplicationThread mAppThread = new ApplicationThread();
继承于ApplicationThreadNative,ApplicationThreadNative继承于Binder实现了IApplicationThread。
resultTo例如以下图所看到的:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamx0eGdjeQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
java层的Parcel,writeStrongBinder方法,最后映射到C++层。运行例如以下:
~/Android/frameworks/base/core/jni
----android_util_Binder.cpp
static void android_os_Parcel_writeStrongBinder(JNIEnv* env, jobject clazz, jobject object)//clazz为Parcel。object指向了在Java层中创建的硬件訪问服务FregService
{
Parcel* parcel = parcelForJavaObject(env, clazz);//获取java层Parcel对象data的引用
if (parcel != NULL) {
const status_t err = parcel->writeStrongBinder(ibinderForJavaObject(env, object));
if (err != NO_ERROR) {
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
}
}
}
ibinderForjavaObject实现例如以下:
~/Android/frameworks/base/core/jni
----android_util_Binder.cpp
sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
{
if (obj == NULL) return NULL; if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
JavaBBinderHolder* jbh = (JavaBBinderHolder*)
env->GetIntField(obj, gBinderOffsets.mObject);//这里把obj对象的mObject成员变量强制转为JavaBBinderHolder对象
return jbh != NULL ? jbh->get(env) : NULL;
} if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
return (IBinder*)
env->GetIntField(obj, gBinderProxyOffsets.mObject);
} LOGW("ibinderForJavaObject: %p is not a Binder object", obj);
return NULL;
}
(1)假设传入的是caller.asBinder(),那么首先生成一个JavaBBinder本地对象。
(2)假设传入的是resultTo,那么生成一个代理对象。
writeStrongBinder实现例如以下:
~/Android/frameworks/base/libs/binder
----Parcel.cpp
status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
{
return flatten_binder(ProcessState::self(), val, this);
}
status_t flatten_binder(const sp<ProcessState>& proc,
const sp<IBinder>& binder, Parcel* out)
{
flat_binder_object obj; obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
if (binder != NULL) {
IBinder *local = binder->localBinder();
if (!local) {
BpBinder *proxy = binder->remoteBinder();
if (proxy == NULL) {
LOGE("null proxy");
}
const int32_t handle = proxy ? proxy->handle() : 0;
obj.type = BINDER_TYPE_HANDLE;
obj.handle = handle;
obj.cookie = NULL;
} else {
obj.type = BINDER_TYPE_BINDER;
obj.binder = local->getWeakRefs();
obj.cookie = local;
}
} else {
obj.type = BINDER_TYPE_BINDER;
obj.binder = NULL;
obj.cookie = NULL;
} return finish_flatten_binder(binder, obj, out);
}
(1)假设是本地对象,obj.cookie为本地对象IBinder地址。
(2)假设是代理对象。obj.handle为代理对象的句柄值。
如图:第二步
Binder Driver:调用binder_transaction:
~/Android//kernel/goldfish/drivers/staging/android
----binder.c
case BINDER_TYPE_BINDER:
case BINDER_TYPE_WEAK_BINDER: {
struct binder_ref *ref;
struct binder_node *node = binder_get_node(proc, fp->binder);
if (node == NULL) {
node = binder_new_node(proc, fp->binder, fp->cookie);
......
}
.......
ref = binder_get_ref_for_node(target_proc, node);
if (ref == NULL) {
return_error = BR_FAILED_REPLY;
goto err_binder_get_ref_for_node_failed;
}
if (fp->type == BINDER_TYPE_BINDER)
fp->type = BINDER_TYPE_HANDLE;
else
fp->type = BINDER_TYPE_WEAK_HANDLE;
fp->handle = ref->desc;
......
} break;
case BINDER_TYPE_HANDLE:
case BINDER_TYPE_WEAK_HANDLE: {
struct binder_ref *ref = binder_get_ref(proc, fp->handle);
......
if (ref->node->proc == target_proc) {
if (fp->type == BINDER_TYPE_HANDLE)
fp->type = BINDER_TYPE_BINDER;
else
fp->type = BINDER_TYPE_WEAK_BINDER;
fp->binder = ref->node->ptr;
fp->cookie = ref->node->cookie;
binder_inc_node(ref->node, fp->type == BINDER_TYPE_BINDER, 0, NULL);
if (binder_debug_mask & BINDER_DEBUG_TRANSACTION)
printk(KERN_INFO " ref %d desc %d -> node %d u%p\n",
ref->debug_id, ref->desc, ref->node->debug_id, ref->node->ptr);
} else {
.......
}
} break;
(1)假设是BINDER_TYPE_BINDER,首先创建实体对象,再创建引用对象。handle为引用句柄值。
(2)假设是BINDER_TYPE_HANDLE,首先获取引用对象。再获取实体对象。cookie为本地对象IBinder的地址。
如图:第三步
~/Android/frameworks/base/core/java/android/app
----ActivityManagerNative.java
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
......
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
case START_ACTIVITY_TRANSACTION:
{
data.enforceInterface(IActivityManager.descriptor);
IBinder b = data.readStrongBinder();
<span style="font-size:14px;">IApplicationThread app = ApplicationThreadNative.asInterface(b);</span>
Intent intent = Intent.CREATOR.createFromParcel(data);
String resolvedType = data.readString();
......
IBinder resultTo = data.readStrongBinder();
......
return true;
}
Parcel类readStrongBinder映射到C++层,运行例如以下:
~/Android/frameworks/base/core/jni
----android_util_Binder.cpp
static jobject android_os_Parcel_readStrongBinder(JNIEnv* env, jobject clazz)
{
Parcel* parcel = parcelForJavaObject(env, clazz);//获得Java层reply的引用
if (parcel != NULL) {
return javaObjectForIBinder(env, parcel->readStrongBinder());
}
return NULL;
}
~/Android/frameworks/base/libs/binder
----Parcel.cpp
sp<IBinder> Parcel::readStrongBinder() const
{
sp<IBinder> val;
unflatten_binder(ProcessState::self(), *this, &val);
return val;
}
status_t unflatten_binder(const sp<ProcessState>& proc,
const Parcel& in, sp<IBinder>* out)
{
const flat_binder_object* flat = in.readObject(false); if (flat) {
switch (flat->type) {
case BINDER_TYPE_BINDER:
*out = static_cast<IBinder*>(flat->cookie);
return finish_unflatten_binder(NULL, *flat, in);
case BINDER_TYPE_HANDLE:
*out = proc->getStrongProxyForHandle(flat->handle);
return finish_unflatten_binder(
static_cast<BpBinder*>(out->get()), *flat, in);
}
}
return BAD_TYPE;
}
(1)假设是BINDER_TYPE_BINDER,返回本地对象。
(2)假设是BINDER_TYPE_HANDLE。依据句柄值,返回代理对象。
然后运行javaObjectForIBinder。
~/Android/frameworks/base/core/jni
----android_util_Binder.cpp
jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
{
if (val == NULL) return NULL; if (val->checkSubclass(&gBinderOffsets)) {
// One of our own!
jobject object = static_cast<JavaBBinder*>(val.get())->object();
........
return object;
} // For the rest of the function we will hold this lock, to serialize
// looking/creation of Java proxies for native Binder proxies.
AutoMutex _l(mProxyLock); // Someone else's... do we know about it?
jobject object = (jobject)val->findObject(&gBinderProxyOffsets);//检查当前进程之前是否已经为它创建过一个BinderProxy对象
if (object != NULL) {//假设有返回来的就是一个指向该BinderProxy对象的WeakReference对象object,即一个弱引用对象
jobject res = env->CallObjectMethod(object, gWeakReferenceOffsets.mGet);//因为弱引用对象object所指向的BinderProxy对象可能已经失效。因此,须要检查它的有效性。方法是调用它的成员函数get来获得一个强引用对象。
if (res != NULL) {//假设不为NULL
......
return res;//直接返回
}
.....
android_atomic_dec(&gNumProxyRefs);//假设为NULL
val->detachObject(&gBinderProxyOffsets);//解除它与一个无效的BinderProxy对象的相应关系
env->DeleteGlobalRef(object);//删除弱引用对象的全局引用
} object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);//创建一个BinderProxy对象
if (object != NULL) {
.......
env->SetIntField(object, gBinderProxyOffsets.mObject, (int)val.get());//BinderProxy.mObject成员变量记录了这个BpBinder对象的地址
val->incStrong(object); // The native object needs to hold a weak reference back to the
// proxy, so we can retrieve the same proxy if it is still active.
jobject refObject = env->NewGlobalRef(
env->GetObjectField(object, gBinderProxyOffsets.mSelf));//获取BinderProxy内部的成员变量mSelf(BinderProxy的弱引用对象)。接着再创建一个全局引用对象来引用它
val->attachObject(&gBinderProxyOffsets, refObject,
jnienv_to_javavm(env), proxy_cleanup);//把它放到BpBinder里面去,下次就要使用时,就能够在上一步调用BpBinder::findObj把它找回来了 // Note that a new object reference has been created.
android_atomic_inc(&gNumProxyRefs);
incRefsCreated(env);
} return object;
}
(1)假设是本地对象。首先向下转型为JavaBBinder,然后取得ActivityRecord对象,它继承了IApplicationToken.Stub。
而IApplicationToken.Stub继承Binder。实现了IApplicationToken。
所以能够向上转型为IBinder。
IBinder resultTo = data.readStrongBinder();
(2)假设是代理对象。首先生成BinderProxy对象,里面的mObject指向代理对象,向上转型为IBinder。
IBinder b = data.readStrongBinder();
IApplicationThread app = ApplicationThreadNative.asInterface(b);
然后生成ActivityManagerProxy对象。里面mRemote指向BinderProxy对象。
如图:第四步
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityManagerService.java
public final class ActivityManagerService extends ActivityManagerNative{ public final int startActivity(IApplicationThread caller,
Intent intent, String resolvedType, Uri[] grantedUriPermissions,
int grantedMode, IBinder resultTo,
String resultWho, int requestCode, boolean onlyIfNeeded,
boolean debug) {
return mMainStack.startActivityMayWait(caller, intent, resolvedType,
grantedUriPermissions, grantedMode, resultTo, resultWho,
requestCode, onlyIfNeeded, debug, null, null);
}
.....
}
主要干了下面几件事:
(1)依据resultTo在ActivityManagerService进程找到用来描写叙述Laucher组件的一个ActivityRecord对象。代码例如以下:
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityStack.java,final int startActivityLocked
ActivityRecord sourceRecord = null;
if (resultTo != null) {
int index = indexOfTokenLocked(resultTo);
.........
if (index >= 0) {
sourceRecord = (ActivityRecord)mHistory.get(index);
........
}
}
(2)依据传递过来的intent创建了一个新的ActivityRecord对象,用来描写叙述即将启动的Activity组件,即MainActivity组件。代码例如以下:
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityStack.java,final int startActivityLocked
ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
intent, resolvedType, aInfo, mService.mConfiguration,
resultRecord, resultWho, requestCode, componentSpecified);
(3)因为须要在新的任务栈中启动Activity,所以设置r.task属性。代码例如以下:
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityStack.java。startActivityUncheckedLocked
if (r.resultTo == null && !addingToTask
&& (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
// todo: should do better management of integers.
......
r.task = new TaskRecord(mService.mCurTask, r.info, intent,
(r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
......
newTask = true;
if (mMainStack) {
mService.addRecentTaskLocked(r.task);
} }
(4)mHistory加入用来描写叙述MainActivity组件的ActivityRecord对象。
代码例如以下:
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityStack.java。private final int startActivityLocked
final int NH = mHistory.size(); int addPos = -1; .......
if (addPos < 0) {
addPos = NH;
} .......
mHistory.add(addPos, r);
(5)ActivityManagerService进程向Laucher子线程发送SCHEDULE_PAUSE_ACTIVITY_TRANSACTION。
代码例如以下:
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityStack.java,private final void startPausingLocked
if (prev.app != null && prev.app.thread != null) {
........
try {
.......
prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
prev.configChangeFlags);
.......
} catch (Exception e) {
.......
}
}
2、总图中的第二步,ActivityManagerService进程向Laucher子线程发送SCHEDULE_PAUSE_ACTIVITY_TRANSACTION
如图:第一步
~/Android/frameworks/base/core/java/android/app
----ApplicationThreadNative.java,ApplicationThreadProxy类
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges) throws RemoteException {
Parcel data = Parcel.obtain();
data.writeInterfaceToken(IApplicationThread.descriptor);
data.writeStrongBinder(token);
data.writeInt(finished ? 1 : 0);
data.writeInt(userLeaving ? 1 :0);
data.writeInt(configChanges);
mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,
IBinder.FLAG_ONEWAY);
data.recycle();
}
当中token是ActivityServiceManager进程的ActivityRecord对象。用来表述Lancher组件。
如图:第二步,省略binder_transaction传输过程,由于上面已经分析过了。
如图:第三步
~/Android/frameworks/base/core/java/android/app
----ApplicationThreadNative.java
public abstract class ApplicationThreadNative extends Binder
implements IApplicationThread {
........
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION:
{
data.enforceInterface(IApplicationThread.descriptor);
IBinder b = data.readStrongBinder();
boolean finished = data.readInt() != 0;
boolean userLeaving = data.readInt() != 0;
int configChanges = data.readInt();
schedulePauseActivity(b, finished, userLeaving, configChanges);
return true;
}
当中b为一个BinderProxy的Binder代理对象。指向了ActivityManagerService中与Laucher组件相应的一个AcitivityRecord对象。
如图:第四步
~/Android/frameworks/base/core/java/android/app
----ActivityThread.java
private final class ApplicationThread extends ApplicationThreadNative {
....... public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges) {
queueOrSendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? 1 : 0),
configChanges);
}
向Laucher主线程发送PAUSE_ACTIVITY_FINISHING命令。
~/Android/frameworks/base/core/java/android/app
----ActivityThread.java
private final class H extends Handler {
.........
public void handleMessage(Message msg) {
.......
switch (msg.what) {
........
case PAUSE_ACTIVITY:
handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
.......
break;
(1)获取了ActivityClientRecord对象,在Lancher进程启动的每个Activity组件都使用一个ActivityClientRecord对象来描写叙述。
(2)Laucher组件运行pause操作。
代码例如以下:
~/Android/frameworks/base/core/java/android/app
----ActivityThread.java
private final void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges) {
ActivityClientRecord r = mActivities.get(token);
if (r != null) {
//Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
if (userLeaving) {
performUserLeavingActivity(r);
} r.activity.mConfigChangeFlags |= configChanges;
Bundle state = performPauseActivity(token, finished, true); // Make sure any pending writes are now committed.
QueuedWork.waitToFinish(); // Tell the activity manager we have paused.
try {
ActivityManagerNative.getDefault().activityPaused(token, state);
} catch (RemoteException ex) {
}
}
}
(3)Laucher主线程向ActivityServiceManager进程发送ACTIVITY_PAUSED_TRANSACTION。
3、Laucher主线程向ActivityServiceManager进程发送ACTIVITY_PAUSED_TRANSACTION
如图:第一步
~/Android/frameworks/base/core/java/android/app
----ActivityManagerNative.java
public void activityPaused(IBinder token, Bundle state) throws RemoteException
{
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(token);
data.writeBundle(state);
mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0);
reply.readException();
data.recycle();
reply.recycle();
}
token为一个BinderProxy的Binder代理对象,指向了ActivityManagerService中与Laucher组件相应的一个AcitivityRecord对象。
如图:第二步,省略binder_transaction传输过程,由于上面已经分析过了。
如图:第三步
~/Android/frameworks/base/core/java/android/app
----ActivityManagerNative.java
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
......
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
case ACTIVITY_PAUSED_TRANSACTION: {
data.enforceInterface(IActivityManager.descriptor);
IBinder token = data.readStrongBinder();
Bundle map = data.readBundle();
activityPaused(token, map);
reply.writeNoException();
return true;
}
.......
}
当中token是ActivityServiceManager进程的ActivityRecord对象,用来表述Lancher组件。
如图:第四步
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityManagerService.java
public final class ActivityManagerService extends ActivityManagerNative{ public final void activityPaused(IBinder token, Bundle icicle) {
// Refuse possible leaked file descriptors
if (icicle != null && icicle.hasFileDescriptors()) {
throw new IllegalArgumentException("File descriptors passed in Bundle");
} final long origId = Binder.clearCallingIdentity();
mMainStack.activityPaused(token, icicle, false);
Binder.restoreCallingIdentity(origId);
}
.....
}
主要做了下面几件事:
(1)创建MainActivity进程。即ProcessRecord对象。
代码例如以下:
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityManagerService.java
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
ProcessRecord app = getProcessRecordLocked(processName, info.uid);
.......
if (app == null) {
app = newProcessRecordLocked(null, info, processName);
.......
} else {
......
}
......
}
(2)开启MainActivity子线程。
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityManagerService.java,startProcessLocked
int pid = Process.start("android.app.ActivityThread",
mSimpleProcessManagement ? app.processName : null, uid, uid,
gids, debugFlags, null);
(3)MainActivity子线程向ActivityManagerService主进程发送ATTACH_APPLICATION_TRANSACTION。
~/Android/frameworks/base/core/java/android/app
----ActivityThread.java
public static final void main(String[] args) {
..... Looper.prepareMainLooper();
......
ActivityThread thread = new ActivityThread();
thread.attach(false);
...... Looper.loop(); ......
}
private final void attach(boolean system) {
.....
mSystemThread = system;
if (!system) {
......
IActivityManager mgr = ActivityManagerNative.getDefault();
try {
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
}
}
.....
}
4、MainActivity子线程向ActivityManagerService主进程发送ATTACH_APPLICATION_TRANSACTION
如图:第一步
~/Android/frameworks/base/core/java/android/app
----ActivityManagerNative.java
class ActivityManagerProxy implements IActivityManager
{ public void attachApplication(IApplicationThread app) throws RemoteException
{
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(app.asBinder());
mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);
reply.readException();
data.recycle();
reply.recycle();
}
......
}
app为:
final ApplicationThread mAppThread = new ApplicationThread();
继承于ApplicationThreadNative,ApplicationThreadNative继承于Binder实现了IApplicationThread。
如图:第二步,省略binder_transaction传输过程。由于上面已经分析过了。
如图:第三步
~/Android/frameworks/base/core/java/android/app
----ActivityManagerNative.java
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
......
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
case ATTACH_APPLICATION_TRANSACTION: {
data.enforceInterface(IActivityManager.descriptor);
IApplicationThread app = ApplicationThreadNative.asInterface(
data.readStrongBinder());
if (app != null) {
attachApplication(app);
}
reply.writeNoException();
return true;
}
.......
}
首先生成BinderProxy对象,里面的mObject指向代理对象,向上转型为IBinder。
然后生成ApplicationThreadProxy对象,里面mRemote指向BinderProxy对象。
如图:第四步
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityManagerService.java
public final class ActivityManagerService extends ActivityManagerNative{ public final void attachApplication(IApplicationThread thread) {
synchronized (this) {
int callingPid = Binder.getCallingPid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid);
Binder.restoreCallingIdentity(origId);
}
}
.....
}
主要做下面几件事:
(1)前面得到的ProcessRecord对象app就是用来描写叙述MainActivity进程的。如今既然MainActivity进程已经启动起来了,那么就继续对ProcessRecord对象app进行初始化,当中最重要的是将它的成员变量thread设置为指向ApplicationThread代理对象。
例如以下图:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamx0eGdjeQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" style="font-size:13.63636302947998px">
代码例如以下:
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityManagerService.java
public final class ActivityManagerService extends ActivityManagerNative{
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid) { /..
ProcessRecord app;
if (pid != MY_PID && pid >= 0) {
synchronized (mPidsSelfLocked) {
app = mPidsSelfLocked.get(pid);
}
} else if (mStartingProcesses.size() > 0) {
.....
} else {
....
} ..... ..... app.thread = thread;
.....
}
(2)r.app = app
代码例如以下:
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityStack.java
final boolean realStartActivityLocked(ActivityRecord r,
ProcessRecord app, boolean andResume, boolean checkConfig)
throws RemoteException { .....
r.app = app;
.....
}
(3)ActivityServiceManager进程向MainActivity子线程发送
~/Android/frameworks/base/services/java/com/android/server/am
----ActivityStack.java
final boolean realStartActivityLocked(ActivityRecord r,
ProcessRecord app, boolean andResume, boolean checkConfig)
throws RemoteException { .....
app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
System.identityHashCode(r),
r.info, r.icicle, results, newIntents, !andResume,
mService.isNextTransitionForward());
.....
}
5、ActivityServiceManager进程向MainActivity子线程发送SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION
如图:第一步
~/Android/frameworks/base/core/java/android/app
----ApplicationThreadNative.java,ApplicationThreadProxy类
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward)
throws RemoteException {
Parcel data = Parcel.obtain();
data.writeInterfaceToken(IApplicationThread.descriptor);
intent.writeToParcel(data, 0);
data.writeStrongBinder(token);
data.writeInt(ident);
info.writeToParcel(data, 0);
data.writeBundle(state);
data.writeTypedList(pendingResults);
data.writeTypedList(pendingNewIntents);
data.writeInt(notResumed ? 1 : 0);
data.writeInt(isForward ? 1 : 0);
mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
IBinder.FLAG_ONEWAY);
data.recycle();
}
当中token是ActivityServiceManager进程的ActivityRecord对象,用来表述MainActivity组件。
如图:第二步。省略binder_transaction传输过程,由于上面已经分析过了。
如图:第三步
~/Android/frameworks/base/core/java/android/app
----ApplicationThreadNative.java
public abstract class ApplicationThreadNative extends Binder
implements IApplicationThread {
........
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
case SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION:
{
data.enforceInterface(IApplicationThread.descriptor);
Intent intent = Intent.CREATOR.createFromParcel(data);
IBinder b = data.readStrongBinder();
int ident = data.readInt();
ActivityInfo info = ActivityInfo.CREATOR.createFromParcel(data);
Bundle state = data.readBundle();
List<ResultInfo> ri = data.createTypedArrayList(ResultInfo.CREATOR);
List<Intent> pi = data.createTypedArrayList(Intent.CREATOR);
boolean notResumed = data.readInt() != 0;
boolean isForward = data.readInt() != 0;
scheduleLaunchActivity(intent, b, ident, info, state, ri, pi,
notResumed, isForward);
return true;
}
.....
}
当中b为一个BinderProxy的Binder代理对象。指向了ActivityManagerService中与MainActivity组件相应的一个AcitivityRecord对象。
接下来,主要做下面几件事:
(1)创建ActivityClientRecord对象。
代码例如以下:
~/Android/frameworks/base/core/java/android/app
----ActivityThread.java
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
ActivityClientRecord r = new ActivityClientRecord();
...
}
(2)通过Handler发送信息给MainActivity主线程
运行mActivity.put(r.token。r),当中r.token为一个BinderProxy的Binder代理对象,指向了ActivityManagerService中与MainActivity组件相应的一个AcitivityRecord对象。
r为刚刚创建的ActivityClientRecord对象。
(3)MainActivity组件运行onCreate操作,最后会调用MainActivity的onCreate方法。
Android Activity组件的启动过程的更多相关文章
- Android源码——Activity组件的启动过程
根Activity启动过程 Launcher启动MainActivity的过程主要分为6个步骤: 一.Launcher向ActivityManagerService发送一个启动MainActivity ...
- Android窗口管理服务WindowManagerService显示Activity组件的启动窗口(Starting Window)的过程分析
文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/8577789 在Android系统中,Activ ...
- Android应用程序进程启动过程的源代码分析
文章转载至CSDN社区罗升阳的安卓之旅,原文地址: http://blog.csdn.net/luoshengyang/article/details/6747696 Android 应用程序框架层创 ...
- Android应用程序进程启动过程(后篇)
前言 在前篇中我们讲到了Android应用程序进程启动过程,这一篇我们来讲遗留的知识点:在应用程序进程创建过程中会启动Binder线程池以及在应用程序进程启动后会创建消息循环. 1.Binder线程池 ...
- tomcat8 源码分析 | 组件及启动过程
tomcat 8 源码分析 ,本文主要讲解tomcat拥有哪些组件,容器,又是如何启动的 推荐访问我的个人网站,排版更好看呦: https://chenmingyu.top/tomcat-source ...
- Android应用程序进程启动过程(前篇)
在此前我讲过Android系统的启动流程,系统启动后,我们就比较关心应用程序是如何启动的,这一篇我们来一起学习Android7.0 应用程序进程启动过程,需要注意的是“应用程序进程启动过程”,而不是应 ...
- Android Activity 四种启动模式
task和back stack(任务和回退栈) 任务启动,task被加入到回退栈的栈顶,返回的时候回退栈的栈顶任务会被弹出,并被销毁,栈中的前一任务恢复运行,当activity销毁是,系统不会保留ac ...
- android activity四种启动模式
1.standard <activity android:name=".MainActivity" android:launchMode="standard&quo ...
- android:Activity四种启动模式简单介绍
Activity启动模式 能够依据实际的需求为Activity设置相应的启动模式,从而能够避免创建大量反复的Activity等问题 Activity有四种载入模式 1.standard(默认启动模式, ...
随机推荐
- javascript必须知道的知识要点(一)
该文章不详细叙述各知识要点的具体内容,仅把要点列出来,供大家学习的时候参照,或者检测自己是否熟练掌握了javascript,清楚各个部分的内容. 语句 注释 输出 字面量 变量 数据类型 typeof ...
- codeforces 712A. Memory and Crow
2019-05-18 08:48:27 加油,加油,坚持!!! 这道题我没有想出公式推导,只是按照模拟题来做,第5个样例超时 样例超时,方法错误 https://www.cnblogs.com/ECJ ...
- RT-Thread 设备驱动SPI浅析及使用
OS版本:RT-Thread 4.0.0 测试BSP:STM32F407 SPI简介 SPI总线框架其实和I2C差不多,可以说都是总线设备+从设备,但SPI设备的通信时序配置并不固定,也就是说控制特定 ...
- ps -aux ,ps aux ,ps -ef 的区别
Linux中的ps命令是Process Status的缩写.ps命令用来列出系统中当前运行的那些进程.ps命令列出的是当前那些进程的快照,就是执行ps命令的那个时刻的那些进程,如果想要动态的显示进程信 ...
- PyQt5.9 Html与本地代码交互实例
在PyQt5.9中, 应用QWebEngineView和QWebChannel技术, 可以进行HTML与本地代码进行交互. 要点: 创建交互对象, 基于QObject, 定义信息槽 创建QWebCha ...
- 使用C语言扩展Python3
使用C语言扩展Python3.在Python3中正确调用C函数. 1. 文件demo.c #include <Python.h> // c function static PyObject ...
- python之路——二分查找算法
楔子 如果有这样一个列表,让你从这个列表中找到66的位置,你要怎么做? l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72 ...
- markdown 计算器
计算器 分四种运算(加减乘除).括号.去除最后括号.验证等式是否计算完成 bracket = re.compile(r'\([^()]+\)') # 找括号 multiplys = re.compil ...
- flex知识点精炼
原址:http://www.runoob.com/w3cnote/flex-grammar.html 容器的属性 设置Flex布局之后,子元素的float.clear.vertical align将失 ...
- LINUX 环境安装 jdk-tomcat安装
linux版本两种安装方式 卸载自带jdk $rpm -qa | grep java $ rpm -e --nodeps java-**-openjdk-*$ rpm -e --nodeps java ...