public static void main(String[] args) {
...
//初始化Looper
Looper.prepareMainLooper();
//创建一个APP主线程ActivityThread对象
ActivityThread thread = newActivityThread();
//初始化App应用信息
thread.attach(false);
//获得主线程也就是UI线程的handler对象
if (sMainThreadHandler == null) {
sMainThreadHandler =thread.getHandler();
}
//Android4.1版本之后添加了这么一个方法,目的就是为了能让AsyncTask能在子线程创建,
//在之前的版本是不能在子线程中创建初始化AsyncTask的。
AsyncTask.init();
//启动Looper循环,进入消息循环。
Looper.loop();
}
private void attach(boolean system) {
//整个应用的Application对象
Application mInitialApplication;
//整个应用的后台管家
Instrumentation mInstrumentation;
...
try {
mInstrumentation = newInstrumentation();
ContextImpl context =ContextImpl.createAppContext(
this,getSystemContext().mPackageInfo);
//利用ContextImpl创建整个应用的Application对象
mInitialApplication =context.mPackageInfo.makeApplication(true, null);
//调用Application对象的onCreate方法
mInitialApplication.onCreate();
}
...
}
public Application makeApplication(booleanforceDefaultAppClass,
Instrumentationinstrumentation) {
//第一次进来mApplication==null条件不满足,之后创建Activity的时候条件满足直接返回当前Application对象
if (mApplication != null) {
return mApplication;
}
Application app = null;
try {
//为Appliaction创建ContextImpl对象
ContextImpl appContext =ContextImpl.createAppContext(mActivityThread, this);
//调用Instrumentation类中的newApplication方法创建Application
app =mActivityThread.mInstrumentation.newApplication(
cl, appClass,appContext);
//给ContextImpl设置外部引用
appContext.setOuterContext(app);
}
...
return app;
}
public Application newApplication(ClassLoadercl, String className, Context context)
throwsInstantiationException, IllegalAccessException,
ClassNotFoundException {
returnnewApplication(cl.loadClass(className), context);
}
static public Application newApplication(Class<?>clazz, Context context)
throwsInstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app =(Application)clazz.newInstance();
app.attach(context);
return app;
}
通过类加载器来创建 Application ,并且调用 attach 来初始化。进入 Application 查看 attach
final void attach(Context context) {
attachBaseContext(context);
mLoadedApk =ContextImpl.getImpl(context).mPackageInfo;
}
private Activity performLaunchActivity(ActivityClientRecordr, Intent customIntent) {
...
Activity activity = null;
try {
//通过Instrumentation类的newActivity方法来创建一个Activity对象
java.lang.ClassLoader cl =r.packageInfo.getClassLoader();
activity =mInstrumentation.newActivity(
cl,component.getClassName(), r.intent);
...
}
try {
//获取当前应用的Application对象,该对象的唯一作用就是作为参数传递到Activity里,
然后在Activity类中可以获得调用getApplication方法来获取Application对象
Application app =r.packageInfo.makeApplication(false, mInstrumentation);
...
if (activity != null) {
//为Activity创建ContextImpl对象
Context appContext =createBaseContextForActivity(r, activity);
//为Activity赋值初始化
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app,r.intent, r.activityInfo, title, r.parent,
r.embeddedID,r.lastNonConfigurationInstances, config,
r.voiceInteractor);
...
//获取当前应用的主题资源
int theme =r.activityInfo.getThemeResource();
if (theme != 0) {
//设置主题
activity.setTheme(theme);
}
activity.mCalled = false;
if (r.isPersistable()) {
//辗转到Activity,调用Activity的生命周期onCreate方法
mInstrumentation.callActivityOnCreate(activity, r.state,r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...
r.activity = activity;
r.stopped = true;
if(!r.activity.mFinished) {
//调用Activity的生命周期onStart方法
activity.performStart();
r.stopped = false;
}
...
return activity;
}
private Context createBaseContextForActivity(ActivityClientRecordr,
final Activity activity) {
ContextImpl appContext =ContextImpl.createActivityContext(this, r.packageInfo, r.token);
// 让 ContextImpl 持有 Activity 对象的引用
appContext.setOuterContext(activity);
Context baseContext = appContext;
...
return baseContext;
}
public final void attach(Context context,ActivityThread aThread,
Instrumentation instr,IBinder token, int ident,
Application application,Intent intent, ActivityInfo info,
CharSequence title, Activityparent, String id,
NonConfigurationInstanceslastNonConfigurationInstances,
Configuration config,IVoiceInteractor voiceInteractor) {
//调用父类方法对mBase变量赋值
attachBaseContext(context);
//创建一个Activity的窗口
mWindow =PolicyManager.makeNewWindow(this);
//给Window窗口设置回调事件
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);
//设置键盘弹出状态
if (info.softInputMode !=WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
mWindow.setSoftInputMode(info.softInputMode);
}
if (info.uiOptions != 0) {
mWindow.setUiOptions(info.uiOptions);
}
mUiThread =Thread.currentThread();
mMainThread = aThread;
mInstrumentation = instr;
mToken = token;
mIdent = ident;
//此处注意,将整个应用的Application对象赋值给Activity的mApplication成员变量。
//目的是为了能在Activity中通过getApplication方法来直接获取Application对象
mApplication = application;
...
}
//在Activity中返回当前应用的Application对象
/** Return the application that owns this activity. */
public final Application getApplication(){
return mApplication;
}
}
private void handleCreateService(CreateServiceDatadata) {
LoadedApk packageInfo =getPackageInfoNoCheck(
data.info.applicationInfo,data.compatInfo);
Service service = null;
try {
//通过类加载器创建Service服务
java.lang.ClassLoader cl =packageInfo.getClassLoader();
service = (Service)cl.loadClass(data.info.name).newInstance();
}
...
try {
...
//此处为Service创建一个ContextImpl对象
ContextImpl context =ContextImpl.createAppContext(this, packageInfo);
//同样为ContextImpl类设置外部对象,目的还是让ContextImpl持有外部类的引用
//在ContextImpl类中的许多方法需要使用到外部Context对象引用
context.setOuterContext(service);
...
//获得当前应用的Applicaton对象,该对象在整个应用中只有一份,是共享的。
Application app =packageInfo.makeApplication(false, mInstrumentation);
//将ContextImpl对象和Application对象作为attach方法参数来初始化Service
service.attach(context, this,data.info.name, data.token, app,
ActivityManagerNative.getDefault());
//Service初始化完成之后系统自动调用onCreate生命周期方法
service.onCreate();
...
}
public final void attach(
Context context,
ActivityThread thread, String className,IBinder token,
Application application,Object activityManager) {
//调用父类方法去注册ContextImpl对象
attachBaseContext(context);
mThread = thread; // NOTE: unused - remove?
mClassName = className;
mToken = token;
//将整个应用的Applicaton对象赋值给Service类的成员变量mApplication
mApplication = application;
mActivityManager =(IActivityManager)activityManager;
}
public class ContextWrapper extends Context{
...
@Override
public Context getApplicationContext(){
returnmBase.getApplicationContext();
}
...
}
class ContextImpl extends Context {
...
@Override
public Context getApplicationContext(){
return (mPackageInfo != null) ?
mPackageInfo.getApplication(): mMainThread.getApplication();
}
...
}
public final Application getApplication() {
return mApplication;
}
package com.xy.bbs;
import android.app.Application;
/**
* Created by mesmerize on 2016/11/1.
*/
public class TestApplication extends Application {
public TestApplication() {
String packageName = this.getPackageName();
System.out.println("ConstructorpackageName = " + packageName);
}
Caused by: java.lang.NullPointerException:Attempt to invoke virtual method 'java.lang.Stringandroid.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at com.xy.bbs.TestApplication.<init>(TestApplication.java:13)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
atcom.android.tools.fd.runtime.BootstrapApplication.createRealApplication(BootstrapApplication.java:215)
atcom.android.tools.fd.runtime.BootstrapApplication.attachBaseContext(BootstrapApplication.java:239)
at android.app.Application.attach(Application.java:189)
...
package com.xy.bbs;
import android.app.Application;
/**
* Created by mesmerize on 2016/11/1.
*/
public class TestApplication extends Application {
@Override
public void onCreate() {
String packageName = this.getPackageName();
System.out.println("onCreate()packageName = " + packageName);
}
}
public class TestApplication extends Application{
private static TestApplicationapplicatioin;
public static TestApplication getInstance(){
if (applicatioin == null) {
applicatioin = newTestApplication();
}
return applicatioin;
}
}
public class TestApplication extends Application{
private static TestApplicationapplication;
public static TestApplication getInstance(){
return application;
}
@Override
public void onCreate() {
super.onCreate();
application = this;
}
}
public class CustomManager {
private static CustomManagersInstance;
public static CustomManager getInstance(Contextcontext) {
if (sInstance == null) {
sInstance = newCustomManager(context);
}
return sInstance;
}
private Context mContext;
private CustomManager(Contextcontext) {
mContext = context;
}
}
public class CustomManager {
private static CustomManagersInstance;
public static CustomManager getInstance(Contextcontext) {
if (sInstance == null) {
//Always pass in theApplication Context
sInstance = newCustomManager(context.getApplicationContext());
}
return sInstance;
}
private Context mContext;
private CustomManager(Contextcontext) {
mContext = context;
}
}
public class CustomResource {
//静态变量drawable
private static Drawable mDrawable;
private View view;
public CustomResource(Contextcontext) {
Resources resources =context.getResources();
mDrawable =resources.getDrawable(R.drawable.ic_launcher);
view = new View(context);
view.setBackgroundDrawable(mDrawable);
}
}
publicvoid setBackgroundDrawable(Drawable background) {
...
/**此处的this就是当前View对象*/
// Set callback last, since theview may still be initializing.
background.setCallback(this);
...
}
357.58 KB, 阅读权限: 10, 下载次数: 11
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |