概述
由之前的源码 我们知道ActivityThread 的创建是在SystemServe中开始的
SystemServer.java run 方法
private void run() {
try {
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
//创建SystemContext 由ActivityThread 创建
createSystemContext();
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
我们先看一下 ActivityThread.systemMain
public static ActivityThread systemMain() {
ActivityThread thread = new ActivityThread();//创建了ActivityThread 对象
thread.attach(true, 0);
return thread;
}
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
}
创建ActivityThread的同时又调用了ContextImpl 的createAppContext 方法 跟下去到了createSystemContext 然后我们这里就创建了ContextImpl对象
static ContextImpl createSystemContext(ActivityThread mainThread) {
LoadedApk packageInfo = new LoadedApk(mainThread);
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null,
null, null, 0,
null, null);
context.setResources(packageInfo.getResources());
context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
context.mResourcesManager.getDisplayMetrics());
return context;
}
然后们看看 这个makeApplication 到底干了什么
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
//applcation 不为空 直接返回
if (mApplication != null) {
return mApplication;
}
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";//Application 的class 名字
}
try {
java.lang.ClassLoader cl = getClassLoader(); //拿到classloader
...........
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
//mInstrumentation
new 出 一个application
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
}
mActivityThread.mAllApplications.add(app);
mApplication = app;
................
return app;
}
newApplication -------->
public Application newApplication(ClassLoader cl, String className, Context context){
Application app = getFactory(context.getPackageName())
.instantiateApplication(cl, className);
app.attach(contxt);//将context 传给Application
return app;
}
instantiateApplication-------->
反射创建Applicaiton
public @NonNull Application instantiateApplication(@NonNull ClassLoader cl,
@NonNull String className){
return (Application) cl.loadClass(className).newInstance();
}
从上面这几块我们可以看到 Application 就创建了 但是这个Application 并不是我们开发出来的应用的Application 我会在之后再写一篇关于应用启动的过程
扯远了 我们回到ActivityThread 看看这货 里面还有啥别的东西 我们从main 方法看看
public static void main(String[] args) {
...........
//?主线成 Looper 在这里创建了。。
Looper.prepareMainLooper();
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
...........
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
//? handler
熟悉吗。。 原来这里也有个Handler
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
}
发现这里也有个handler 我们看看 它这个handler 是啥
class H extends Handler {
此处省略一万行原代码
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
case EXIT_APPLICATION:
if (mInitialApplication != null) {
mInitialApplication.onTerminate();
}
Looper.myLooper().quit();
break;
case RECEIVER:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
handleReceiver((ReceiverData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
case CREATE_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
handleCreateService((CreateServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
case BIND_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
handleBindService((BindServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
............
case RELAUNCH_ACTIVITY:
handleRelaunchActivityLocally((IBinder) msg.obj);
break;
}
看这个case 大概也能猜出来一些吧。。 什么 我们调用的 bindservice createservice 原来都是在这里处理的。 也是消息机制 接收的。有兴趣的大家可以再 详细看看 源码 很多 平时用的东西这里都能看到
然后我们看看 这个main 方法里面的attach 方法 上面看了一下 attach 是 system server 调用的 ,我们看到它的参数前一个是boolean 值 如果是正常App 启动 这个boolean 值是false 所以我们看看源码
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
} else {
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true,
mInitialApplication.onCreate();
}
}
上面的代码 我们看到 如果不是system 走if 逻辑 调用了IActivityManager 的 attachApplication 方法 IActivityManager 就是ActivityManagerService
ActiviyManagerService.java
attachApplication()-------->
public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
Binder.restoreCallingIdentity(origId);
}
}
attachApplicationLocked ----->
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
...省略一万行代码
thread.bindApplication(processName, appInfo, providers,
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);
}
ActivityThread.java
thread.bindApplication--->
public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, 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) {
//发送消息给handler
sendMessage(H.BIND_APPLICATION, data);
}
handler---->
public void handleMessage(Message msg) {
switch (msg.what) {
case BIND_APPLICATION:
handleBindApplication(data);
break;
}
handleBindApplication ---->
private void handleBindApplication(AppBindData data) {
Application app;
try {
data.info 其实就是loadApk 对象
app = data.info.makeApplication(data.restrictedBackupMode, null);
}
LoadApk.java
makeApplication----->
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
//如果存在直接返回
if (mApplication != null) {
return mApplication;
}
Application app = null;
try {
java.lang.ClassLoader cl = getClassLoader();
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
mActivityThread.mAllApplications.add(app);
mApplication = app;
if (instrumentation != null) {
try {
// 这里是调用了Application的Oncreate 方法
instrumentation.callApplicationOnCreate(app);
}
}
上面这一圈儿 就是想 给大家看下 App 启动以后 Application 为什么是首先创建的。。
最后回顾一下从Init 到ActivityThread的整体流程
系统开机 进行一些系统启动加载 硬件初始化等 -----> 加载Init 进程 -----> 解析init.rc ------> 创建了zygote ,servicemanager 等系统进程 -----> zygote fork 出systemserver 进程 ------> jni 调用Systemserver.java 的run 方法-----> 开启其他服务 ams wms 等等 以及 创建了ActivityThread 还有就是开启了Launcher Activity 我们看到了桌面
最后
以上就是顺心招牌为你收集整理的Android FrameWork 之ActivityThread 源码的全部内容,希望文章能够帮你解决Android FrameWork 之ActivityThread 源码所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复