android service原理

整体考虑:
两种方式启动服务startService和bindService。
startService方式,不需要service返回数据,通过AMS将数据转发给Service即可,异步。简化考虑,AMS作为转发中介,需要维护service列表,以便于将数据转发给service,因此service在启动之后需要告知AMS--publishService;AMS和service的交互是跨进程操作,需要使用Binder方式传递数据,所以通过publishService传递给AMS的数据中需要包含一个Binder对象(或者直接通过IApplicationThread执行,那么需要传递进来一个查找service的token);要做转发因此需要进行路由,那么很重要的一部分是如何实现路由,查找到对应的service?通过intent来查找,如果intent指定了componentName,那么就能精确的查找到对应的service,如果没有指定,可以通过action,type,data等进行匹配,那么匹配的对象是一组组的intent-filter,因此ams对service进行索引时与intent-filter有关,那么是否就是以intent-filter为key呢?
如果service是首次启动,ams中service列表肯定是匹配不到的,需要查找到对应的进程,所有的service都在manifest中注册过,因此可以通过PMS来进行查找,获取到的信息中会包含进程信息和intent-filter等信息。找到对应的进程后,需要检测进程是否存活,存活的进程都会持有IApplicationThread对象,可以作为一个依据,如果进程没有启动,需要把service加入mPendingService队列,启动进程,启动进程之后app调用AMS#attachApplication,AMS会回调bindApplication,之后再启动四大组件之类的;如果进程已经启动,通过realStartService启动service。在service的生命周期至少有两部分,一个为onCreate,一个为onStartCommand,因此onCreate之后,需要通过AMS,再继续执行serviceDoneExecuting通知更新service状态。

startservice代码

关键类:ServiceRecord,ServiceRecord.StartItem对象

// ServiceRecord  为IBinder 对象,并且定义了重新拉起的次数等
final class ServiceRecord extends Binder implements ComponentName.WithComponentName {
    private static final String TAG = TAG_WITH_CLASS_NAME ? "ServiceRecord" : TAG_AM;

    // Maximum number of delivery attempts before giving up.
    static final int MAX_DELIVERY_COUNT = 3;

    // Maximum number of times it can fail during execution before giving up.
    static final int MAX_DONE_EXECUTING_COUNT = 6;
    final ArrayMap bindings
            = new ArrayMap();
                            // All active bindings to the service.
    final ArrayMap> connections
            = new ArrayMap>();
    static class StartItem {
        final ServiceRecord sr;
        final boolean taskRemoved;
        final int id;
        final int callingId;
        final Intent intent;
        final ActivityManagerService.NeededUriGrants neededGrants;
        long deliveredTime;
        int deliveryCount;
        int doneExecutingCount;
        UriPermissionOwner uriPermissions;

        String stringName;      // caching of toString
     }
}

ServiceRecord 为IBinder 对象,并且定义了重新拉起的次数等。

bindservice代码

关键类:ContextImpl,ServiceConnection
contextImpl#bindService---->contextImpl.bindServiceCommon

private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,   
         UserHandle user) {                                                             
     IServiceConnection sd;                                                                                                                                          
     if (mPackageInfo != null) {                                            
         sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),                
                 mMainThread.getHandler(), flags);                                      
     }                                                                               
     validateServiceIntent(service);                                                    
     try {                                                                              
         IBinder token = getActivityToken();                                            
         //省略一些代码。                                                           
         service.prepareToLeaveProcess();                                               
         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;                                                                  
     }                                                                                  
 }     

其中sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
mMainThread.getHandler(), flags);
可以看到代码中也调用了service.resolveTypeIfNeeded(getContentResolver(),接下来代码转入AMS中。
AMS#bindService--> ActiveService#realStartServiceLocked

   private final void realStartServiceLocked(ServiceRecord r,
            ProcessRecord app, boolean execInFg) throws RemoteException {
        if (app.thread == null) {
            throw new RemoteException();
        }
        requestServiceBindingsLocked(r, execInFg);
   }

requestServiceBindingLocked:

private final boolean requestServiceBindingLocked(ServiceRecord r,
        IntentBindRecord i, boolean execInFg, boolean rebind) {
    if (r.app == null || r.app.thread == null) {
        // If service is not currently running, can't yet bind.
        return false;
    }
    if ((!i.requested || rebind) && i.apps.size() > 0) {
        try {
            bumpServiceExecutingLocked(r, execInFg, "bind");
            r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
            r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
                    r.app.repProcState);
            if (!rebind) {
                i.requested = true;
            }
            i.hasBound = true;
            i.doRebind = false;
        } catch (RemoteException e) {
            if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
            return false;
        }
    }
    return true;
}

通过 r.app.thread#scheduleBindService给应用进程发送消息

public final void scheduleBindService(IBinder token, Intent intent,
        boolean rebind, int processState) {
    updateProcessState(processState, false);
    BindServiceData s = new BindServiceData();
    s.token = token;
    s.intent = intent;
    s.rebind = rebind;
    Binder.getCallingPid());
    sendMessage(H.BIND_SERVICE, s);
}

接下来转入service所在的进程:

case BIND_SERVICE:
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
    handleBindService((BindServiceData)msg.obj);
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    break;

handleBindService:

private void handleBindService(BindServiceData data) {
    //从记录中获取一个service对象,每次启动Service,系统都会记录到mServices中
    Service s = mServices.get(data.token);
    if (s != null) {
        try {
            data.intent.setExtrasClassLoader(s.getClassLoader());
            try {
                //判断service是否未绑定过了
                if (!data.rebind) {
                    //没有绑定需要走onBind
                    IBinder binder = s.onBind(data.intent);
                    ActivityManagerNative.getDefault().publishService(
                            data.token, data.intent, binder);
                } else {
                    //绑定过需要走onRebind
                    s.onRebind(data.intent);
                    ActivityManagerNative.getDefault().serviceDoneExecuting(
                            data.token, 0, 0, 0);
                }
                ensureJitEnabled();
            } catch (RemoteException ex) {
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(s, e)) {
                throw new RuntimeException(
                        "Unable to bind to service " + s
                        + " with " + data.intent + ": " + e.toString(), e);
            }
        }
    }
}

其中的data.token为AMS中使用的ServiceRecord,前面提到继承自Binder。依据是否绑定过,决定执行onBind还是onReBind,前者会调用AMS#publishService,后者会调用AMS#serviceDoneExecuting方法。

publishService中调用了ActiveService#publishServiceLocked

for (int conni=r.connections.size()-1; conni>=0; conni--) {
    ArrayList clist = r.connections.valueAt(conni);
    for (int i=0; i

ConnectionRecord中保存有IServiceConnection,前面提到在bindService时,根据ServiceConnection,生成ServiceDispatcher会以Context为单位管理ServiceConnection,LoadedApk对广播和ContentProvider也有类似的管理逻辑。

public final IServiceConnection getServiceDispatcher(ServiceConnection c,
        Context context, Handler handler, int flags) {
    synchronized (mServices) {
        LoadedApk.ServiceDispatcher sd = null;
        ArrayMap map = mServices.get(context);
        if (map != null) {
            sd = map.get(c);
        }
        if (sd == null) {
            sd = new ServiceDispatcher(c, context, handler, flags);
            if (map == null) {
                map = new ArrayMap();
                mServices.put(context, map);
            }
            map.put(c, sd);
        } else {
            sd.validate(context, handler);
        }
        return sd.getIServiceConnection();
    }
}

getIServiceConnection中以弱引用的方式持有mDispatcher,原因为何?因为InnerConnection是ServiceDispatcher静态内部类,而不是内部类。(代码组织方式)

static final class ServiceDispatcher {
        private final ServiceDispatcher.InnerConnection mIServiceConnection;
        private final ServiceConnection mConnection;
        private final Context mContext;
        private final Handler mActivityThread;
        private final ServiceConnectionLeaked mLocation;
        private final int mFlags;

        private RuntimeException mUnbindLocation;

        private boolean mForgotten;

        private static class ConnectionInfo {
            IBinder binder;
            IBinder.DeathRecipient deathMonitor;
        }

        private static class InnerConnection extends IServiceConnection.Stub {
            final WeakReference mDispatcher;

            InnerConnection(LoadedApk.ServiceDispatcher sd) {
                mDispatcher = new WeakReference(sd);
            }

            public void connected(ComponentName name, IBinder service, boolean dead)
                    throws RemoteException {
                LoadedApk.ServiceDispatcher sd = mDispatcher.get();
                if (sd != null) {
                    sd.connected(name, service, dead);
                }
            }
        }

        private final ArrayMap mActiveConnections
            = new ArrayMap();

        ServiceDispatcher(ServiceConnection conn,
                Context context, Handler activityThread, int flags) {
            mIServiceConnection = new InnerConnection(this);
            mConnection = conn;
            mContext = context;
            mActivityThread = activityThread;
            mLocation = new ServiceConnectionLeaked(null);
            mLocation.fillInStackTrace();
            mFlags = flags;
        }

ServiceDispatcher#connected:

public void connected(ComponentName name, IBinder service, boolean dead) {
            if (mActivityThread != null) {
                mActivityThread.post(new RunConnection(name, service, 0, dead));
            } else {
                doConnected(name, service, dead);
            }
        }

public void doConnected(ComponentName name, IBinder service, boolean dead) {
            ServiceDispatcher.ConnectionInfo old;
            ServiceDispatcher.ConnectionInfo info;

            synchronized (this) {
                if (mForgotten) {
                    // We unbound before receiving the connection; ignore
                    // any connection received.
                    return;
                }
                old = mActiveConnections.get(name);
                if (old != null && old.binder == service) {
                    // Huh, already have this one.  Oh well!
                    return;
                }

                if (service != null) {
                    // A new service is being connected... set it all up.
                    info = new ConnectionInfo();
                    info.binder = service;
                    info.deathMonitor = new DeathMonitor(name, service);
                    try {
                        service.linkToDeath(info.deathMonitor, 0);
                        mActiveConnections.put(name, info);
                    } catch (RemoteException e) {
                        // This service was dead before we got it...  just
                        // don't do anything with it.
                        mActiveConnections.remove(name);
                        return;
                    }

                } else {
                    // The named service is being disconnected... clean up.
                    mActiveConnections.remove(name);
                }

                if (old != null) {
                    old.binder.unlinkToDeath(old.deathMonitor, 0);
                }
            }

            // If there was an old service, it is now disconnected.
            if (old != null) {
                mConnection.onServiceDisconnected(name);
            }
            if (dead) {
                mConnection.onBindingDied(name);
            }
            // If there is a new viable service, it is now connected.
            if (service != null) {
                mConnection.onServiceConnected(name, service);
            } else {
                // The binding machinery worked, but the remote returned null from onBind().
                mConnection.onNullBinding(name);
            }
        }

通过IServiceConnection持有的ServiceDispatcher执行connect方法

重点

  1. AMS在转发数据时有两个要点,类似的模式也出现在ContentProvider中:
    a. AMS通过IApplicationThread通知Service#bindService,Service通过publishService传递给AMS生成的Binder,并记录在AMS的ActiveService中,Service进程中的Service记录和ActiveService中的记录一一对应的依据是ServiceRecord。
    a. AMS以ServiceRecord为单元维护LoadedApk.ServiceDispatcher中生成的IServiceConnection对象,Server端通过publishService中传递参数IBinder,并触发从ServiceRecord中查找待绑定的IServiceConnection列表,并执行回调。

你可能感兴趣的:(android service原理)