public abstract class Context{
...
// 启动 Activity
public abstract void startActivity(Intentintent);
// 获取系统服务
public abstract Object getSystemService(Stringname);
// 发送广播
public abstract void sendBroadcast(Intentintent);
// 开启 Service
public abstract ComponentName startService(Intentservice);
public abstract AssetManager getAssets();
public abstract Resources getResources();
public abstract PackageManager getPackageManager();
...
}
class ContextImpl extends Context {
//整个App的主线程
final ActivityThread mMainThread;
//整个App的相关信息
final LoadedApk mPackageInfo;
//资源解析器
private final ResourcesManagermResourcesManager;
//App资源类
private final Resources mResources;
//外部Context的引用
private Context mOuterContext;
//默认主题
private int mThemeResource = 0;
private Resources.Theme mTheme = null;
//包管理器
private PackageManagermPackageManager;
...
//以下是静态区注册系统的各种服务,多达五六十种系统服务,因此每个持有Context引用的对象都可以随时通过getSystemService方法来轻松获取系统服务。
static {
registerService(ACCESSIBILITY_SERVICE, new ServiceFetcher() {
public Object getService(ContextImplctx) {
returnAccessibilityManager.getInstance(ctx);
}});
registerService(CAPTIONING_SERVICE, new ServiceFetcher() {
public Object getService(ContextImplctx) {
return newCaptioningManager(ctx);
}});
registerService(ACCOUNT_SERVICE, newServiceFetcher() {
public Object createService(ContextImplctx) {
IBinder b =ServiceManager.getService(ACCOUNT_SERVICE);
IAccountManager service =IAccountManager.Stub.asInterface(b);
return newAccountManager(ctx, service);
}});
...
}
...
//启动Activity的地方
@Override
public void startActivity(Intent intent,Bundle options) {
warnIfCallingFromSystemProcess();
if((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
throw newAndroidRuntimeException(
"CallingstartActivity() from outside of an Activity " +
" context requiresthe FLAG_ACTIVITY_NEW_TASK flag." +
" Is this reallywhat you want?");
}
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(),mMainThread.getApplicationThread(), null,
(Activity)null, intent, -1,options);
}
...
//启动服务的地方
@Override
public ComponentName startService(Intentservice) {
warnIfCallingFromSystemProcess();
return startServiceCommon(service,mUser);
}
...
}
public class ContextWrapper extends Context{
Context mBase;
// 给mBase赋值
public ContextWrapper(Context base){
mBase = base;
}
// 创建Application、Service、Activity的时候会调用该方法,给mBase赋值,若mBase早已赋值,会抛出状态非法异常
protected void attachBaseContext(Contextbase) {
if(mBase != null) {
throw newIllegalStateException("mBase context already set");
mBase = base;
}
}
...
public Context getBaseContext() {
return mBase;
}
@Override
public AssetManager getAssets() {
return mBase.getAssets();
}
@Override
public Resources getResources() {
return mBase.getResources();
}
@Override
public ContentResolver getContentResolver(){
return mBase.getContentResolver();
}
@Override
public Looper getMainLooper() {
return mBase.getMainLooper();
}
@Override
public Context getApplicationContext(){
return mBase.getApplicationContext();
}
@Override
public String getPackageName() {
return mBase.getPackageName();
}
@Override
public void startActivity(Intentintent) {
mBase.startActivity(intent);
}
@Override
public void sendBroadcast(Intentintent) {
mBase.sendBroadcast(intent);
}
@Override
public Intent registerReceiver(
BroadcastReceiver receiver,IntentFilter filter) {
return mBase.registerReceiver(receiver,filter);
}
@Override
public void unregisterReceiver(BroadcastReceiverreceiver) {
mBase.unregisterReceiver(receiver);
}
@Override
public ComponentName startService(Intentservice) {
return mBase.startService(service);
}
@Override
public boolean stopService(Intentname) {
return mBase.stopService(name);
}
@Override
public boolean bindService(Intentservice, ServiceConnection conn,
int flags) {
return mBase.bindService(service,conn, flags);
}
@Override
public void unbindService(ServiceConnectionconn) {
mBase.unbindService(conn);
}
@Override
public Object getSystemService(Stringname) {
return mBase.getSystemService(name);
}
...
}
public class ContextThemeWrapper extends ContextWrapper{
private int mThemeResource;
private Resources.Theme mTheme;
private LayoutInflater mInflater;
private ConfigurationmOverrideConfiguration;
private Resources mResources;
public ContextThemeWrapper() {
super(null);
}
public ContextThemeWrapper(Contextbase, @StyleRes int themeResId) {
super(base);
mThemeResource = themeResId;
}
public ContextThemeWrapper(Contextbase, Resources.Theme theme) {
super(base);
mTheme = theme;
}
@Override
protected void attachBaseContext(ContextnewBase) {
super.attachBaseContext(newBase);
}
}
//创建Application时同时创建的ContextIml实例
private final void handleBindApplication(AppBindData data){
...
///创建Application对象
Application app = data.info.makeApplication(data.restrictedBackupMode,null);
...
}
public Application makeApplication(boolean forceDefaultAppClass,Instrumentation instrumentation) {
...
try {
java.lang.ClassLoader cl =getClassLoader();
//创建一个ContextImpl对象实例
ContextImpl appContext = newContextImpl();
//初始化该ContextIml实例的相关属性
appContext.init(this, null,mActivityThread);
///新建一个Application对象
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass,appContext);
//将该Application实例传递给该ContextImpl实例
appContext.setOuterContext(app);
}
...
}
Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1,options);
} else {
// Note we want to go through this call forcompatibility with
// applications that may haveoverridden the method.
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermissionIntent intent, int requestCode,@Nullable Bundle options) {
if (mParent == null) {
Instrumentation.ActivityResult ar=
mInstrumentation.execStartActivity(
this,mMainThread.getApplicationThread(), mToken, this,
intent, requestCode,options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID,requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
// If this start isrequesting a result, we can avoid making
// the activity visible untilthe result is received. Setting
// this code duringonCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden duringthis time, to avoid flickering.
// This can only be done whena result is requested because
// that guarantees we willget information back when the
// activity is finished, nomatter what happens to it.
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
// TODO Considerclearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go throughthis method for compatibility with
// existing applications thatmay have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
private void handleLaunchActivity(ActivityClientRecordr, Intent customIntent, String reason) {
// If we are getting ready to gcafter going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
mSomeActivitiesChanged = true;
if (r.profilerInfo != null) {
mProfiler.setProfiler(r.profilerInfo);
mProfiler.startProfiling();
}
// Make sure we are running with themost recent config.
handleConfigurationChanged(null, null);
if (localLOGV) Slog.v(
TAG, "Handling launch of" + r);
// Initialize before creating theactivity
WindowManagerGlobal.initialize();
// 在这里启动一个 Activity
Activity a = performLaunchActivity(r,customIntent);
if (a != null) {
r.createdConfig = newConfiguration(mConfiguration);
reportSizeConfigurations(r);
Bundle oldState = r.state;
handleResumeActivity(r.token, false,r.isForward,
!r.activity.mFinished&& !r.startsNotResumed, r.lastProcessedSeq, reason);
if (!r.activity.mFinished&& r.startsNotResumed) {
// The activity manageractually wants this one to start out paused, because it
// needs to be visible butisn't in the foreground. We accomplish this by going
// through the normal startup(because activities expect to go through onResume()
// the first time they run,before their window is displayed), and then pausing it.
// However, in this case wedo -not- need to do the full pause cycle (of freezing
// and such) because theactivity manager assumes it can just retain the current
// state it has.
performPauseActivityIfNeeded(r, reason);
// We need to keep around theoriginal state, in case we need to be created again.
// But we only do this forpre-Honeycomb apps, which always save their state when
// pausing, so we can nothave them save their state when restarting from a paused
// state. For HC and later,we want to (and can) let the state be saved as the
// normal part of stoppingthe activity.
if (r.isPreHoneycomb()) {
r.state = oldState;
}
}
} else {
// If there was an error, for anyreason, tell the activity manager to stop us.
try {
ActivityManagerNative.getDefault()
.finishActivity(r.token,Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throwex.rethrowFromSystemServer();
}
}
}
/**
主要做了以下几件事
1. 从ActivityClientRecord中获取待启动act的组件信息;
2. 通过Instrumentation.newActivity方法使用ClassLoader创建act对象;
3. 通过LoadedApk.makeApplication方法创建Application对象,注意如果已经有Application对象的话是不会再次创建的;
4. 创建ComtextImpl对象,并调用Activity.attach方法完成一些重要数据的初始化操作;
5. 最终调用Activity.onCreate()方法;
*/
private Activity performLaunchActivity(ActivityClientRecord r, IntentcustomIntent) {
//System.out.println("##### [" + System.currentTimeMillis() + "]ActivityThread.performLaunchActivity(" + r + ")");
ActivityInfo aInfo =r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo =getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component =r.intent.getComponent();
if (component == null) {
component =r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity!= null) {
component = newComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity =mInstrumentation.newActivity(
cl,component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if(!mInstrumentation.onException(activity, e)) {
throw newRuntimeException(
"Unable toinstantiate activity " + component
+ ": " +e.toString(), e);
}
}
try {
Application app =r.packageInfo.makeApplication(false, mInstrumentation);
if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
if (localLOGV) Slog.v(
TAG, r + ":app=" + app
+ ",appName=" + app.getPackageName()
+ ", pkg=" +r.packageInfo.getPackageName()
+ ", comp="+ r.intent.getComponent().toShortString()
+ ", dir=" +r.packageInfo.getAppDir());
if (activity != null) {
Context appContext =createBaseContextForActivity(r, activity);
CharSequence title =r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = newConfiguration(mCompatConfiguration);
if (r.overrideConfig != null){
config.updateFrom(r.overrideConfig);
}
if (DEBUG_CONFIGURATION)Slog.v(TAG, "Launching activity "
+r.activityInfo.name + " with config " + config);
Window window = null;
if (r.mPendingRemoveWindow!= null && r.mPreserveWindow) {
window =r.mPendingRemoveWindow;
r.mPendingRemoveWindow= null;
r.mPendingRemoveWindowManager = null;
}
activity.attach(appContext,this, getInstrumentation(), r.token,
r.ident, app,r.intent, r.activityInfo, title, r.parent,
r.embeddedID,r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor,window);
if (customIntent != null){
activity.mIntent =customIntent;
}
r.lastNonConfigurationInstances = null;
activity.mStartedActivity= false;
int theme =r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity,r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
throw newSuperNotCalledException(
"Activity" + r.intent.getComponent().toShortString() +
" did notcall through to super.onCreate()");
}
r.activity = activity;
r.stopped = true;
if (!r.activity.mFinished){
activity.performStart();
r.stopped = false;
}
if (!r.activity.mFinished){
if (r.isPersistable()){
if (r.state != null ||r.persistentState != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
r.persistentState);
}
} else if (r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
if (!r.activity.mFinished){
activity.mCalled = false;
if (r.isPersistable()){
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnPostCreate(activity, r.state);
}
if (!activity.mCalled){
throw newSuperNotCalledException(
"Activity" + r.intent.getComponent().toShortString() +
" did not call through tosuper.onPostCreate()");
}
}
}
r.paused = true;
mActivities.put(r.token, r);
} catch (SuperNotCalledExceptione) {
throw e;
} catch (Exception e) {
if(!mInstrumentation.onException(activity, e)) {
throw newRuntimeException(
"Unable to startactivity " + component
+ ": " +e.toString(), e);
}
}
return activity;
}
if(activity != null) {
// 创建一个 Activity
ContextImpl appContext = newContextImpl();
// 初始化该 ContextImpl 实例的相关属性
appContext.init(r.packageInfo,r.token,this);
// 将该 Activity 信息传递给该ContextImpl 实例
appContext.setOuterContext(activity);
}
//创建一个Service实例时同时创建ContextIml实例
private final void handleCreateService(CreateServiceData data){
...
//创建一个Service实例
Service service = null;
try {
java.lang.ClassLoader cl =packageInfo.getClassLoader();
service = (Service)cl.loadClass(data.info.name).newInstance();
} catch (Exception e) {
}
...
ContextImpl context = newContextImpl(); //创建一个ContextImpl对象实例
context.init(packageInfo, null, this); //初始化该ContextIml实例的相关属性
//获得我们之前创建的Application对象信息
Application app =packageInfo.makeApplication(false, mInstrumentation);
//将该Service信息传递给该ContextImpl实例
context.setOuterContext(service);
...
}
357.58 KB, 阅读权限: 10, 下载次数: 4
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |