前面已经介绍了如何创建一个应用服务,如何创建一个系统服务,这里我把Android服务分为:应用服务(ActivityService),系统服务(SystemService),分类是否正确也不清楚,网上并没有资料明确定义,之所以这样分类,因为应用服务放在ActiveServices中管理,而系统服务放在ServiceManager中管理,两者存在明显的不同。由于Android设计时已经把中间层标准化了,我们实现一个服务时,只需要简单实现服务端(Native)和调用端(Proxy)即可。本文将详细描述ActiveService的启动全过程,有关Binder的部分没有详细介绍,后续文章再介绍。
public class ContextWrapper extends Context { Context mBase; public ContextWrapper(Context base) { mBase = base; } ... public boolean bindService(Intent service, ServiceConnection conn, int flags) { return mBase.bindService(service, conn, flags); } ... }再看ContextThemeWrapper
public class ContextThemeWrapper extends ContextWrapper { ... public ContextThemeWrapper() { super(null); } ... }而Activity没有构造函数,这说明我们new一个Activity时,mBase是null,那怎么bindService呢?一定有一个地方设置了mBase。在《Android进阶-Activity应用启动分析》一文中写到ActivityThread.performLaunchActivity函数有介绍。现在继续这个函数:
public ActivityThread{ private Context createBaseContextForActivity(ActivityClientRecord r, final Activity activity) { ContextImpl appContext = new ContextImpl(); appContext.init(r.packageInfo, r.token, this); appContext.setOuterContext(activity); ... Context baseContext = appContext; ... return baseContext; } ... private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")"); ... try { Application app = r.packageInfo.makeApplication(false, mInstrumentation); ... if (activity != null) { //创建上下文 Context appContext = createBaseContextForActivity(r, activity); CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); Configuration config = new Configuration(mCompatConfiguration); if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity " + r.activityInfo.name + " with config " + config); //连接上下文 activity.attach(appContext, this, getInstrumentation(), r.token, r.ident, app, r.intent, r.activityInfo, title, r.parent, r.embeddedID, r.lastNonConfigurationInstances, config); ... } r.paused = true; mActivities.put(r.token, r); } catch (SuperNotCalledException e) { throw e; } catch (Exception e) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to start activity " + component + ": " + e.toString(), e); } } return activity; } }frameworks/base/core/java/android/app/Activity.java
public Activity{ ... final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token, int ident, Application application, Intent intent, ActivityInfo info, CharSequence title, Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances, Configuration config) { // 连接mBase attachBaseContext(context); mFragments.attachActivity(this, mContainer, null); ... } }frameworks/base/core/java/android/view/ContextThemeWrapper.java
public class ContextThemeWrapper{ protected void attachBaseContext(Context newBase) { //连接mBase super.attachBaseContext(newBase); mBase = newBase; } }从上面的源代码可以看出,当载入Activity类后,便会调用createBaseContextForActivity来创建appContext,再用activity.attach来连接context。而appContext是用newContextImpl()来创建的,所以,Activity.mBase就是一个ContextImpl的类实例。
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, UserHandle user) { IServiceConnection sd; if (conn == null) { throw new IllegalArgumentException("connection is null"); } if (mPackageInfo != null) { // 创建一个IServiceConnection对象,服务绑定后,需要调用此对象的connected函数,触发ServiceConnection.onServiceConnected事件 // 此对象是一个LoadedApk.ServiceDispatcher.InnerConnection对象,见后面的LoadedApk的代码解释 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), mMainThread.getHandler(), flags); } else { throw new RuntimeException("Not supported in system context"); } validateServiceIntent(service); try { ... // 通过ActivieyManagerProxy.bindService,经由Binder调用ActivityManagerService.bindService int res = ActivityManagerNative.getDefault().bindService( mMainThread.getApplicationThread(), getActivityToken(), service, service.resolveTypeIfNeeded(getContentResolver()), sd, flags, user.getIdentifier()); if (res < 0) { throw new SecurityException( "Not allowed to bind to service " + service); } return res != 0; } catch (RemoteException e) { return false; } }frameworks/base/core/java/android/app/LoadedApk.java
public class LoadedApk{ ... static final class ServiceDispatcher { private final ServiceDispatcher.InnerConnection mIServiceConnection; ... private static class InnerConnection extends IServiceConnection.Stub { ... } ... IServiceConnection getIServiceConnection() { // 返回一个InnerConnection连接 return mIServiceConnection; } } ... public final IServiceConnection getServiceDispatcher(ServiceConnection c, Context context, Handler handler, int flags) { synchronized (mServices) { LoadedApk.ServiceDispatcher sd = null; ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context); if (map != null) { sd = map.get(c); } if (sd == null) { // 创建ServiceDispatcher sd = new ServiceDispatcher(c, context, handler, flags); if (map == null) { map = new ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>(); mServices.put(context, map); } map.put(c, sd); } else { sd.validate(context, handler); } // 返回ServiceDispatcher.getIServiceConnection() return sd.getIServiceConnection(); } } ... }本函数做两个事情:
public class ActiveServices{ ... private final String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting) { ... ProcessRecord app; if (!isolated) { app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false); if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app); if (app != null && app.thread != null) { // 如果服务进程已经启动 try { app.addPackage(r.appInfo.packageName, mAm.mProcessStats); realStartServiceLocked(r, app, execInFg); return null; } catch (RemoteException e) { Slog.w(TAG, "Exception when starting service " + r.shortName, e); } // If a dead object exception was thrown -- fall through to // restart the application. } } else { ... } // Not running -- get it started, and enqueue this service record // to be executed when the app comes up. if (app == null) { // 如果服务进程未启动 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags, "service", r.name, false, isolated, false)) == null) { ... return msg; } if (isolated) { r.isolatedProc = app; } } ... return null; } }
public clas ActivityThread{ ... private void handleCreateService(CreateServiceData data) { // If we are getting ready to gc after going to the background, well // we are back active so skip it. unscheduleGcIdler(); LoadedApk packageInfo = getPackageInfoNoCheck( data.info.applicationInfo, data.compatInfo); Service service = null; try { java.lang.ClassLoader cl = packageInfo.getClassLoader(); service = (Service) cl.loadClass(data.info.name).newInstance(); } catch (Exception e) { if (!mInstrumentation.onException(service, e)) { throw new RuntimeException( "Unable to instantiate service " + data.info.name + ": " + e.toString(), e); } } try { if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name); ContextImpl context = new ContextImpl(); context.init(packageInfo, null, this); Application app = packageInfo.makeApplication(false, mInstrumentation); context.setOuterContext(service); // 连接服务上下文 service.attach(context, this, data.info.name, data.token, app, ActivityManagerNative.getDefault()); // 触发服务的onCreate事件 service.onCreate(); mServices.put(data.token, service); try { ActivityManagerNative.getDefault().serviceDoneExecuting( data.token, 0, 0, 0); } catch (RemoteException e) { // nothing to do. } } catch (Exception e) { if (!mInstrumentation.onException(service, e)) { throw new RuntimeException( "Unable to create service " + data.info.name + ": " + e.toString(), e); } } } }
public class ActivityThread{ ... private void handleBindService(BindServiceData data) { Service s = mServices.get(data.token); if (DEBUG_SERVICE) Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind); if (s != null) { try { data.intent.setExtrasClassLoader(s.getClassLoader()); try { if (!data.rebind) { // 触发服务的onBind事件 IBinder binder = s.onBind(data.intent); // 通过Binder,调用ActivityManagerService.publishService发布服务 ActivityManagerNative.getDefault().publishService( data.token, data.intent, binder); } else { ... } ensureJitEnabled(); } catch (RemoteException ex) { } } catch (Exception e) { ... } } } }
pulbic class ActivityManagerService{ ... public void publishService(IBinder token, Intent intent, IBinder service) { // Refuse possible leaked file descriptors if (intent != null && intent.hasFileDescriptors() == true) { throw new IllegalArgumentException("File descriptors passed in Intent"); } synchronized(this) { if (!(token instanceof ServiceRecord)) { throw new IllegalArgumentException("Invalid service token"); } mServices.publishServiceLocked((ServiceRecord)token, intent, service); } } ... }frameworks/base/services/java/com/android/server/am/ActiveServices.java
pulbic class ActiveService{ ... void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) { final long origId = Binder.clearCallingIdentity(); try { if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r + " " + intent + ": " + service); if (r != null) { Intent.FilterComparison filter = new Intent.FilterComparison(intent); IntentBindRecord b = r.bindings.get(filter); if (b != null && !b.received) { b.binder = service; b.requested = true; b.received = true; for (int conni=r.connections.size()-1; conni>=0; conni--) { ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni); for (int i=0; i<clist.size(); i++) { ConnectionRecord c = clist.get(i); ... try { // c.conn 为 服务启动准备阶段 在ContextImpl.bindServiceCommon中创建的,为一个LoadedApk.ServiceDispatcher.InnerConnection的实例。 c.conn.connected(r.name, service); } catch (Exception e) { Slog.w(TAG, "Failure sending service " + r.name + " to connection " + c.conn.asBinder() + " (in " + c.binding.client.processName + ")", e); } } } } serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false); } } finally { Binder.restoreCallingIdentity(origId); } } ... }
public class LoadApk{ ... static final class ServiceDispatcher { private static class InnerConnection extends IServiceConnection.Stub { final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher; InnerConnection(LoadedApk.ServiceDispatcher sd) { mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd); } // 通知已经连接 public void connected(ComponentName name, IBinder service) throws RemoteException { LoadedApk.ServiceDispatcher sd = mDispatcher.get(); if (sd != null) { // 进入下面的connected函数 sd.connected(name, service); } } } ... public void connected(ComponentName name, IBinder service) { if (mActivityThread != null) { mActivityThread.post(new RunConnection(name, service, 0)); } else { // 进入下面的doConnected函数 doConnected(name, service); } } ... public void doConnected(ComponentName name, IBinder service) { ServiceDispatcher.ConnectionInfo old; ServiceDispatcher.ConnectionInfo info; ... // If there was an old service, it is not disconnected. if (old != null) { // 假如是服务,触发onServiceDisconnected事件 mConnection.onServiceDisconnected(name); } // If there is a new service, it is now connected. if (service != null) { // 假如是新服务,则触发onServiceConnected。mConnection为在Activity.bindService是传入的参数,也即是绑定服务前用户创建的ServiceConnection类实例。 mConnection.onServiceConnected(name, service); } } } }
Android 进阶 - Activity服务启动分析,布布扣,bubuko.com
原文:http://blog.csdn.net/szzhaom/article/details/23452939