service啟動流程
阿新 • • 發佈:2020-08-15
startService
1 public class ContextWrapper extends Context { 2 Context mBase; 3 ...... 4 protected void attachBaseContext(Context base) { 5 if (mBase != null) { 6 throw new IllegalStateException("Base context already set"); 7 } 8 mBase = base;9 } 10 ...... 11 @Override 12 public ComponentName startService(Intent service) { 13 return mBase.startService(service); 14 } 15 ...... 16 }
mBase來歷
1 //====ActivityThread.java===== 2 private Activity performLaunchActivity(...){ 3 ...... 4 ContextImpl appContext = createBaseContextForActivity(r); //程式碼① 5 Activity activity = null; 6 ...... 7 activity.attach(appContext,...);//程式碼② 8 ...... 9 } 10 11 //跟進程式碼① 12 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) { 13 ...... 14 ContextImpl appContext = ContextImpl.createActivityContext( 15 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig); 16 ...... 17 return appContext; 18 } 19 20 //==========ContextImpl.java======= 21 static ContextImpl createActivityContext(...){ 22 ...... 23 ContextImpl context = new ContextImpl(...); 24 ..... 25 return context; 26 } 27 28 //跟進程式碼② 29 //======Activity.java extends ContextThemeWrapper extends ContextThemeWrapper extends ContextWrapper extends Context=== 30 final void attach(Context context,...){ 31 attachBaseContext(context); 32 ...... 33 } 34 35 protected void attachBaseContext(Context newBase) { 36 super.attachBaseContext(newBase); 37 ...... 38 } 39 40 //======ContextThemeWrapper.java====== 41 @Override 42 protected void attachBaseContext(Context newBase) { 43 super.attachBaseContext(newBase); 44 } 45 //========ContextWrapper.java===== 46 protected void attachBaseContext(Context base) { 47 if (mBase != null) { 48 throw new IllegalStateException("Base context already set"); 49 } 50 mBase = base; 51 }
所以mBase就是ContextImpl的例項。
1 class ContextImpl extends Context { 2 ...... 3 }
/
1 @Override 2 public ComponentName startService(Intent service) { 3 warnIfCallingFromSystemProcess(); 4 return startServiceCommon(service, false, mUser); 5 } 6 7 private ComponentName startServiceCommon(Intent service, boolean requireForeground, 8 UserHandle user) { 9 try { 10 ...... 11 ComponentName cn = ActivityManager.getService().startService( 12 mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded( 13 getContentResolver()), requireForeground, 14 getOpPackageName(), user.getIdentifier()); 15 ...... 16 return cn; 17 } catch (RemoteException e) { 18 throw e.rethrowFromSystemServer(); 19 } 20 }
在上一篇文章中提到過,ActivityManager.getService()實際上就是獲取AMS在當前程序的遠端代理Proxy,這裡不贅述了。
dd