第一步Launcher.startActivitySafely()
说明:在Android系统中,应用程序是由Launcher启动起来的,其实,Launcher本身也是一个应用程序,其它的应用程序安装后,就会Launcher的界面上出现一个相应的图标,点击这个图标时,Launcher就会对应的应用程序启动起来。
/**
* Default launcher application.
*/
public final class Launcher extends Activity
implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, AllAppsView.Watcher {
......
/**
* Launches the intent referred by the clicked shortcut.
*
* @param v The view representing the clicked shortcut.
*/
public void onClick(View v) {
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
// Open shortcut
final Intent intent = ((ShortcutInfo) tag).intent;
int[] pos = new int[2];
v.getLocationOnScreen(pos);
intent.setSourceBounds(new Rect(pos[0], pos[1],
pos[0] + v.getWidth(), pos[1] + v.getHeight()));
startActivitySafely(intent, tag);
} else if (tag instanceof FolderInfo) {
......
} else if (v == mHandleView) {
......
}
}
void startActivitySafely(Intent intent, Object tag) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
......
} catch (SecurityException e) {
......
}
}
......
}
第二步:Activity.startActivity()
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks {
......
@Override
public void startActivity(Intent intent) {
startActivityForResult(intent, -1);
}
......
}
第三步:Activtiy.startActivityForResult()
说明:
(1)mMainThread也是Activity类的成员变量,它的类型是ActivityThread,它代表的是应用程序的主线程。
(2)通过mMainThread.getApplicationThread获得它里面的ApplicationThread成员变量,它是一个Binder对象,后面我们会看到,ActivityManagerService会使用它来和ActivityThread来进行进程间通信。
(3)这里的mMainThread代表的是Launcher应用程序运行的进程。
(4)mToken也是Activity类的成员变量,它是一个Binder对象的远程接口。
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks {
......
public void startActivityForResult(Intent intent, int requestCode) {
if (mParent == null) {
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode);
......
} else {
......
}
......
}
第四步:Instrumentation.execStartActivity()
(1)Intent.resolveTypeIfNeeded返回这个intent的MIME类型
(2)Instrumentation.checkStartActivityResult():检查启动Activity的结果,会抛出各种异常,如Activity没有注册。
(3)ActivityManagetNative:继承IActivityManager接口;相当于Stub(运行在SystemServer进程)
ActivityManagerService:实现了ActivityManagetNative抽象类
ActivityManagerNative.getDefault():返回ActivityMangerProxy;相当于Proxy(运行在应用程序进程)
public class Instrumentation {
......
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
if (mActivityMonitors != null) {
......
}
try {
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
null, 0, token, target != null ? target.mEmbeddedID : null,
requestCode, false, false);
......
} catch (RemoteException e) {
}
return null;
}
......
}
第五步:ActivityManagerNative.getDefalut.startActivity()
参数grantedUriPermissions和resultWho均为null;
参数caller为ApplicationThread类型的Binder实体;
参数resultTo为一个Binder实体的远程接口,我们先不关注它;
参数grantedMode为0,我们也先不关注它;
参数requestCode为-1;
参数onlyIfNeeded和debug均空false。
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.writeString(resolvedType);
data.writeTypedArray(grantedUriPermissions, 0);
data.writeInt(grantedMode);
data.writeStrongBinder(resultTo);
data.writeString(resultWho);
data.writeInt(requestCode);
data.writeInt(onlyIfNeeded ? 1 : 0);
data.writeInt(debug ? 1 : 0);
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
reply.readException();
int result = reply.readInt();
reply.recycle();
data.recycle();
return result;
}
......
}
ActivityManagerProxy和ActivityManagerNative
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
//从类声明上,我们可以看到ActivityManagerNative是Binder的一个子类,而且实现了IActivityManager接口
static public IActivityManager getDefault() {
return gDefault.get();
}
//通过单例模式获取一个IActivityManager对象,这个对象通过asInterface(b)获得
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
}
//最终返回的还是一个ActivityManagerProxy对象
static public IActivityManager asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IActivityManager in =
(IActivityManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
//这里面的Binder类型的obj参数会作为ActivityManagerProxy的成员变量保存为mRemote成员变量,负责进行IPC通信
return new ActivityManagerProxy(obj);
}
第六步:ActivityManagerService.startActivity()
(1)将操作转发给成员变量mMainStack的startActivityMayWait函数,这里的mMainStack的类型为ActivityStack。
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
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);
}
......
}
第七步: ActivityStack.startActivityMayWait()
public class ActivityStack {
......
final int startActivityMayWait(IApplicationThread caller,
Intent intent, String resolvedType, Uri[] grantedUriPermissions,
int grantedMode, IBinder resultTo,
String resultWho, int requestCode, boolean onlyIfNeeded,
boolean debug, WaitResult outResult, Configuration config) {
......
boolean componentSpecified = intent.getComponent() != null;
// Don't modify the client's object!
intent = new Intent(intent);
// Collect information about the target of the Intent.
ActivityInfo aInfo;
try {
ResolveInfo rInfo =
AppGlobals.getPackageManager().resolveIntent(
intent, resolvedType,
PackageManager.MATCH_DEFAULT_ONLY
| ActivityManagerService.STOCK_PM_FLAGS);
aInfo = rInfo != null ? rInfo.activityInfo : null;
} catch (RemoteException e) {
......
}
if (aInfo != null) {
// Store the found target back into the intent, because now that
// we have it we never want to do this again. For example, if the
// user navigates back to this point in the history, we should
// always restart the exact same activity.
intent.setComponent(new ComponentName(
aInfo.applicationInfo.packageName, aInfo.name));
......
}
synchronized (mService) {
int callingPid;
int callingUid;
if (caller == null) {
......
} else {
callingPid = callingUid = -1;
}
mConfigWillChange = config != null
&& mService.mConfiguration.diff(config) != 0;
......
if (mMainStack && aInfo != null &&
(aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
......
}
int res = startActivityLocked(caller, intent, resolvedType,
grantedUriPermissions, grantedMode, aInfo,
resultTo, resultWho, requestCode, callingPid, callingUid,
onlyIfNeeded, componentSpecified);
if (mConfigWillChange && mMainStack) {
......
}
......
if (outResult != null) {
......
}
return res;
}
}
......
}
第六步:在ActivityStack和ActivitySupervisior之间来回调用方法
第七步:ActivityStackSupervisor.realStartActivityLocked()
第八步:AppliactionThreadProxy.scheduleLauchActivity()(SystemServer进程+Binder通信过程)
过程:通过Handler H发送一条消息给 H处理。
说明:
AppliactionThread:继承AppliactionThreadNative;ActivityThread的内部类,负责ActivityThread和AMS之间的通信;相当于Stub实现类
ApplicationThreadProxy:实现IApplicationThread;相当于Proxy;
AAppliactionThreadNative:相当于Stub;实现IApplicationThread。
第九步:ActivityThread.handleLaunchActivity()
过程:调用ActivityThread.performLauchActivity()
第十步:ActivityThread.performLauchActivity()
(1)从ActivityClientRecord中获取待启动的Activity的组件信息
(2)通过Instrumentation的newActivity方法使用类加载器创建Activity对象
(3)通过LoadedApk的makeApplication方法来尝试创建Application对象。
(4)创建ContextImpl对象,并通过Activity的attach方法来完成一些重要数据的初始化。
(5)调用Activity的onCreate方法
总结
一. Launcher通过Binder进程间通信机制通知ActivityManagerService,它要启动一个Activity;
二. ActivityManagerService通过Binder进程间通信机制通知Launcher进入Paused状态;
三. Launcher通过Binder进程间通信机制通知ActivityManagerService,它已经准备就绪进入Paused状态,于是ActivityManagerService就创建一个新的进程,用来启动一个ActivityThread实例,即将要启动的Activity就是在这个ActivityThread实例中运行;
四. ActivityThread通过Binder进程间通信机制将一个ApplicationThread类型的Binder对象传递给ActivityManagerService,以便以后ActivityManagerService能够通过这个Binder对象和它进行通信;
五. ActivityManagerService通过Binder进程间通信机制通知ActivityThread,现在一切准备就绪,它可以真正执行Activity的启动操作了。