Android知识点之Service

1、service 启动流程(Android 11)

(1)、启动服务流程(同进程)

a、应用内调用到AMS过程

在Activity环境下调用startService方法 frameworks/base/core/java/android/content/ContextWrapper.java

public ComponentName startService(Intent service) {
    //mBase就是Activity在启动时在ActivityThread中创建的ContextImpl.java对象
    return mBase.startService(service);
}
复制代码

frameworks/base/core/java/android/app/ContextImpl.java

public ComponentName startService(Intent service) {
    ····
    return startServiceCommon(service, false, mUser);
}

private ComponentName startServiceCommon(Intent service, boolean requireForeground,
                                         UserHandle user) {
    try {
        ····
        //通过Binder机制跨进程调用AMS的startService方法
        ComponentName cn = ActivityManager.getService().startService(
                mMainThread.getApplicationThread(), service,
                service.resolveTypeIfNeeded(getContentResolver()), requireForeground,
                getOpPackageName(), getAttributionTag(), user.getIdentifier());
        ····
        return cn;
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
复制代码

frameworks/base/core/java/android/app/ActivityManager.java

public static IActivityManager getService() {
    return IActivityManagerSingleton.get();
}

@UnsupportedAppUsage
private static final Singleton<IActivityManager> IActivityManagerSingleton =
        new Singleton<IActivityManager>() {
            @Override
            protected IActivityManager create() {
                //IActivityManager是Binder机制实现接口类
                //ServiceManager是缓存Binder的实现对象,通过getService()可以获取到跨进程通信的Binder实现对象
                //例如WMS、PMS等都可以通过这个ServiceManager对象获取到
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                final IActivityManager am = IActivityManager.Stub.asInterface(b);
                return am;
            }
        };
复制代码

至此,启动服务就进入了SystemServer进程继续工作

b、AMS处理以及调用ActivityThread过程

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public ComponentName startService(IApplicationThread caller, Intent service,
                                  String resolvedType, boolean requireForeground, String callingPackage,
                                  String callingFeatureId, int userId)
        throws TransactionTooLargeException {
    ····
    synchronized(this) {
        ···
        ComponentName res;
        try {
            //mServices对应的是ActiveServices.java对象
            //caller为ActivityThread中的ApplicationThread的Binder机制实现类,用于与应用进程通信
            res = mServices.startServiceLocked(caller, service,
                    resolvedType, callingPid, callingUid,
                    requireForeground, callingPackage, callingFeatureId, userId);
        }
        ····
        return res;
    }
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
                                 int callingPid, int callingUid, boolean fgRequired, String callingPackage,
                                 @Nullable String callingFeatureId, final int userId)
        throws TransactionTooLargeException {
    return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
            callingPackage, callingFeatureId, userId, false);
}

ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
                                 int callingPid, int callingUid, boolean fgRequired, String callingPackage,
                                 @Nullable String callingFeatureId, final int userId,
                                 boolean allowBackgroundActivityStarts) throws TransactionTooLargeException {
    ····
    //一切准备就绪,调用此处来启动服务
    ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
    ····
    return cmp;
}

ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
                                      boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
    ····
    //启动服务
    String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
    ····
    return r.name;
}

private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
                                    boolean whileRestarting, boolean permissionsReviewRequired)
        throws TransactionTooLargeException {
    ····
    final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
    ····
    ProcessRecord app;
    //判断启动的服务进程是否存在
    if (!isolated) {
        app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
        ···
        if (app != null && app.thread != null) {
            try {
                ····
                //存在则直接启动服务
                realStartServiceLocked(r, app, execInFg);
                return null;
            }
            ···
        }
    } else {
        //启动的服务进程不存在,需要创建HostingRecord辅助开启创建进程
        if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
            hostingRecord = HostingRecord.byAppZygote(r.instanceName, r.definingPackageName,
                    r.definingUid);
        }
    }
    //启动的服务进程不存在,创建一个新的进程
    if (app == null && !permissionsReviewRequired) {
        //启动一个新进程
        if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
                hostingRecord, ZYGOTE_POLICY_FLAG_EMPTY, false, isolated, false)) == null) {
            ····
        }
        ····
    }
    ····
    return null;
}

private final void realStartServiceLocked(ServiceRecord r,
                                          ProcessRecord app, boolean execInFg) throws RemoteException {
    ····
    //启动ANR弹窗任务,当启动前台服务超过20s或者后台服务超过200s时,会弹ANR系统窗口提示应用无响应
    bumpServiceExecutingLocked(r, execInFg, "create");
    ····
    try {
        ····
        //跨进程调用应用ActivityThread对象,进而调用service的onCreate生命周期方法
        app.thread.scheduleCreateService(r, r.serviceInfo,
                mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
                app.getReportedProcState());
        ····
        created = true;
    } catch (DeadObjectException e) {
        ····
    } finally {
        //启动出现异常,那么ANR弹窗任务需要移除掉
        if (!created) {
            ····
            serviceDoneExecutingLocked(r, inDestroying, inDestroying);
            ····
        }
    }
    //跨进程调用应用ActivityThread对象,进而调用service的onStartCommand生命周期方法
    //绑定服务在这个方法中会限制调用,不会调用service的onStartCommand生命周期方法
    sendServiceArgsLocked(r, execInFg, true);
    ····
}

private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
                                         boolean oomAdjusted) throws TransactionTooLargeException {
    ····
    while (r.pendingStarts.size() > 0) {
        ···
        //启动ANR弹窗任务,当启动前台服务超过20s或者后台服务超过200s时,会弹ANR系统窗口提示应用无响应
        bumpServiceExecutingLocked(r, execInFg, "start");
        ···
    }
    ····
    try {
        //通过跨进程调用应用进程的ActivityThread的ApplicationThread中的scheduleServiceArgs启动服务
        r.app.thread.scheduleServiceArgs(r, slice);
    } catch (TransactionTooLargeException e) {
        ···
        caughtException = e;
    } catch (RemoteException e) {
        ····
        caughtException = e;
    } catch (Exception e) {
        ····
        caughtException = e;
    }
    if (caughtException != null) {
        ···
        for (int i = 0; i < args.size(); i++) {
            //启动出现异常,那么ANR弹窗任务需要移除掉
            serviceDoneExecutingLocked(r, inDestroying, inDestroying);
        }
        ···
    }
}
复制代码

service启动在SystemServer进程需要判断是否需要创建新进程,还需要监测service启动的超时时间,除此之后还需要判断权限等等,最终通过Binder机制调用应用进程方法调用service生命周期方法

c、应用ActivityThread处理过程

service的onCreate生命周期方法流程 frameworks/base/core/java/android/app/ActivityThread.java

public final void scheduleCreateService(IBinder token,
                                        ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
    updateProcessState(processState, false);
    CreateServiceData s = new CreateServiceData();
    s.token = token;
    s.info = info;
    s.compatInfo = compatInfo;
    //向主线程发送一条消息
    sendMessage(H.CREATE_SERVICE, s);
}

class H extends Handler {
    public void handleMessage(Message msg) {
        ····
        switch (msg.what) {
            ····
            case CREATE_SERVICE:
                ····
                //主线程处理Server启动
                handleCreateService((CreateServiceData) msg.obj);
                ····
                break;
            ····
        }
    }
}

private void handleCreateService(CreateServiceData data) {
        ····
    try {
        ····
        service.attach(context, this, data.info.name, data.token, app,
                ActivityManager.getService());
        //调用Server生命周期方法
        service.onCreate();
        ····
        try {
            //调用AMS的serviceDoneExecuting方法移除Server超时监测任务
            ActivityManager.getService().serviceDoneExecuting(
                    data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    } catch (Exception e) {
        ····
    }
}
复制代码

service的onStartCommand生命周期方法流程 frameworks/base/core/java/android/app/ActivityThread.java

public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
    List<ServiceStartArgs> list = args.getList();
    for (int i = 0; i < list.size(); i++) {
        ServiceStartArgs ssa = list.get(i);
        ServiceArgsData s = new ServiceArgsData();
        s.token = token;
        s.taskRemoved = ssa.taskRemoved;
        s.startId = ssa.startId;
        s.flags = ssa.flags;
        s.args = ssa.args;
        //向主线程发送一条消息
        sendMessage(H.SERVICE_ARGS, s);
    }
}

class H extends Handler {
    public void handleMessage(Message msg) {
        ····
        switch (msg.what) {
            ····
            case SERVICE_ARGS:
                ····
                //处理服务启动
                handleServiceArgs((ServiceArgsData) msg.obj);
                ····
                break;
            ····    
        }
    }
}

private void handleServiceArgs(ServiceArgsData data) {
    Service s = mServices.get(data.token);
    if (s != null) {
        try {
            ····
            if (!data.taskRemoved) {
                //调用service的onStartCommand生命周期方法
                res = s.onStartCommand(data.args, data.flags, data.startId);
            } 
            ····
            try {
                //跨进程调用AMS方法将ANR任务移除
                ActivityManager.getService().serviceDoneExecuting(
                        data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
            } 
            ···
        } catch (Exception e) {
            ····
        }
    }
}
复制代码

(2)、绑定服务流程(同进程)

a、应用内调用到AMS过程

在Activity环境下调用bindService方法 frameworks/base/core/java/android/content/ContextWrapper.java

public boolean bindService(Intent service, ServiceConnection conn,
        int flags) {
    //mBase就是Activity在启动时在ActivityThread中创建的ContextImpl.java对象
    return mBase.bindService(service, conn, flags);
}
复制代码

frameworks/base/core/java/android/app/ContextImpl.java

public boolean bindService(Intent service, ServiceConnection conn, int flags) {
    ····
    return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,
            getUser());
}

private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
                                  String instanceName, Handler handler, Executor executor, UserHandle user) {
    IServiceConnection sd;
    ····
    //创建一个IServiceConnection的binder实现对象,内部封装ServiceConnection对象
    //该对象传输到AMS所在进程中,AMS通过IServiceConnection的binder实现对象可以调用应用中IServiceConnection实现方法
    if (mPackageInfo != null) {
        //当在绑定服务调用bindService方法有传入Executor对象,则executor不为null
        if (executor != null) {
            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
        } else {
            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
        }
    }
    ····
    try {
        ····
        //通过Binder机制跨进程调用AMS的bindIsolatedService方法
        //sd为IServiceConnection对象,是一个Binder实现类,通过封装ServiceConnection得到
        //sd的作用也是跨进程通信,当通过bindIsolatedService方法进入AMS进程处理时,
        //AMS通过需要绑定的服务的`public IBinder onBind(Intent intent)`方法获取到一个自定义的Binder对象实现类,
        //通过sd的connected方法将这个自定义的Binder实现类回传到应用进程ServiceConnection类的onServiceConnected方法中
        //这个自定义的Binder实现类可以跨进程通信,绑定的服务是不同进程的可以通过这个参数跨进程通信
        int res = ActivityManager.getService().bindIsolatedService(
                mMainThread.getApplicationThread(), getActivityToken(), service,
                service.resolveTypeIfNeeded(getContentResolver()),
                sd, flags, instanceName, getOpPackageName(), user.getIdentifier());
        ····
        return res != 0;
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
复制代码

IServiceConnection的binder实现对象创建过程 frameworks/base/core/java/android/app/LoadedApk.java

public final IServiceConnection getServiceDispatcher(ServiceConnection c,
                                                     Context context, Handler handler, int flags) {
    return getServiceDispatcherCommon(c, context, handler, null, flags);
}

public final IServiceConnection getServiceDispatcher(ServiceConnection c,
                                                     Context context, Executor executor, int flags) {
    return getServiceDispatcherCommon(c, context, null, executor, flags);
}

private IServiceConnection getServiceDispatcherCommon(ServiceConnection c,
                                                      Context context, Handler handler, Executor executor, int flags) {
    synchronized (mServices) {
        ·····
        //当在绑定服务调用bindService方法有传入Executor对象,则executor不为null
        if (executor != null) {
            sd = new ServiceDispatcher(c, context, executor, flags);
        } else {
            sd = new ServiceDispatcher(c, context, handler, flags);
        }
        ····
        return sd.getIServiceConnection();
    }
}

static final class ServiceDispatcher {

    private final ServiceDispatcher.InnerConnection mIServiceConnection;
    
    //创建出IServiceConnection对象
    private static class InnerConnection extends IServiceConnection.Stub {
        ····
    }
    
    ServiceDispatcher(ServiceConnection conn,
                      Context context, Handler activityThread, int flags) {
        mIServiceConnection = new InnerConnection(this);
        ····
    }

    ServiceDispatcher(ServiceConnection conn,
                      Context context, Executor activityExecutor, int flags) {
        mIServiceConnection = new InnerConnection(this);
        ····
    }

    IServiceConnection getIServiceConnection() {
        return mIServiceConnection;
    }
}
复制代码
b、AMS处理以及调用ActivityThread过程

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service,
                               String resolvedType, IServiceConnection connection, int flags, String instanceName,
                               String callingPackage, int userId) throws TransactionTooLargeException {
    ····
    synchronized(this) {
        //mServices对应的是ActiveServices.java对象
        //caller为ActivityThread中的ApplicationThread的Binder机制实现类,用于与应用进程通信
        //connection为IServiceConnection的Binder机制实现类,用于与应用进程通信
        return mServices.bindServiceLocked(caller, token, service,
                resolvedType, connection, flags, instanceName, callingPackage, userId);
    }
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
                      String resolvedType, final IServiceConnection connection, int flags,
                      String instanceName, String callingPackage, final int userId)
        throws TransactionTooLargeException {
    ····
    //flags在绑定过程的时候传的是Context.BIND_AUTO_CREATE,即是1
    if ((flags & Context.BIND_AUTO_CREATE) != 0) {
        s.lastActivity = SystemClock.uptimeMillis();
        //启动服务
        if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
                permissionsReviewRequired) != null) {
            return 0;
        }
    }
    ····
    return 1;
}

private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
                                    boolean whileRestarting, boolean permissionsReviewRequired)
        throws TransactionTooLargeException {
    ····
    final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
    ····
    ProcessRecord app;
    //判断启动的服务进程是否存在
    if (!isolated) {
        app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
        ···
        if (app != null && app.thread != null) {
            try {
                ····
                //存在则直接启动服务
                realStartServiceLocked(r, app, execInFg);
                return null;
            }
            ···
        }
    } else {
        //启动的服务进程不存在,需要创建HostingRecord辅助开启创建进程
        if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
            hostingRecord = HostingRecord.byAppZygote(r.instanceName, r.definingPackageName,
                    r.definingUid);
        }
    }
    //启动的服务进程不存在,创建一个新的进程
    if (app == null && !permissionsReviewRequired) {
        //启动一个新进程
        if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
                hostingRecord, ZYGOTE_POLICY_FLAG_EMPTY, false, isolated, false)) == null) {
            ····
        }
        ····
    }
    ····
    return null;
}

private final void realStartServiceLocked(ServiceRecord r,
                                          ProcessRecord app, boolean execInFg) throws RemoteException {
    ····
    //启动ANR弹窗任务,当启动前台服务超过20s或者后台服务超过200s时,会弹ANR系统窗口提示应用无响应
    bumpServiceExecutingLocked(r, execInFg, "create");
    ····
    try {
        ····
        //跨进程调用应用ActivityThread对象,进而调用service的onCreate生命周期方法
        app.thread.scheduleCreateService(r, r.serviceInfo,
                mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
                app.getReportedProcState());
        ····
        created = true;
    } catch (DeadObjectException e) {
        ····
    } finally {
        //启动出现异常,那么ANR弹窗任务需要移除掉
        if (!created) {
            ····
            serviceDoneExecutingLocked(r, inDestroying, inDestroying);
            ····
        }
    }
    ···
    //如果是绑定服务,那么需要把自定义的Binder对象通过IServiceConnection回传
    requestServiceBindingsLocked(r, execInFg);
    ···
}
复制代码

绑定服务是有自定义的Binder对象,这个需要通过AMS回传到应用进程中,也就是回传到ActivityThread里,看到requestServiceBindingsLocked方法的操作 frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
        throws TransactionTooLargeException {
    for (int i=r.bindings.size()-1; i>=0; i--) {
        //只有是绑定服务当前IntentBindRecord对象才有具体绑定的设置值
        IntentBindRecord ibr = r.bindings.valueAt(i);
        if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
            break;
        }
    }
}

private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
                                                  boolean execInFg, boolean rebind) throws TransactionTooLargeException {
    ····
    //防止重复绑定判断
    if ((!i.requested || rebind) && i.apps.size() > 0) {
        try {
            ···
            //调用应用进程ActivityThread中的ApplicatonThread的scheduleBindService方法,进行数据回传
            r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
                    r.app.getReportedProcState());
            //防止重复绑定的限制
            if (!rebind) {
                i.requested = true;
            }
            ····
        } catch (TransactionTooLargeException e) {
            ····
            //绑定出现异常,那么ANR弹窗任务需要移除掉
            serviceDoneExecutingLocked(r, inDestroying, inDestroying);
            throw e;
        } catch (RemoteException e) {
            ···
            //绑定出现异常,那么ANR弹窗任务需要移除掉
            serviceDoneExecutingLocked(r, inDestroying, inDestroying);
            return false;
        }
    }
    return true;
}
复制代码
c、应用ActivityThread处理过程

service的onCreate生命周期方法流程 frameworks/base/core/java/android/app/ActivityThread.java

public final void scheduleCreateService(IBinder token,
                                        ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
    updateProcessState(processState, false);
    CreateServiceData s = new CreateServiceData();
    s.token = token;
    s.info = info;
    s.compatInfo = compatInfo;
    //向主线程发送一条消息
    sendMessage(H.CREATE_SERVICE, s);
}

class H extends Handler {
    public void handleMessage(Message msg) {
        ····
        switch (msg.what) {
            ····
            case CREATE_SERVICE:
                ····
                //主线程处理Server启动
                handleCreateService((CreateServiceData) msg.obj);
                ····
                break;
            ····
        }
    }
}

private void handleCreateService(CreateServiceData data) {
        ····
    try {
        ····
        service.attach(context, this, data.info.name, data.token, app,
                ActivityManager.getService());
        //调用Server生命周期方法
        service.onCreate();
        ····
        try {
            //调用AMS的serviceDoneExecuting方法移除Server超时监测任务
            ActivityManager.getService().serviceDoneExecuting(
                    data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    } catch (Exception e) {
        ····
    }
}
复制代码

绑定service的onBind或者onRebind生命周期方法流程 frameworks/base/core/java/android/app/ActivityThread.java

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;
    ....
    //向主线程发送一条消息
    sendMessage(H.BIND_SERVICE, s);
}

class H extends Handler {
    public void handleMessage(Message msg) {
    ····
        switch (msg.what) {
        ····
            case BIND_SERVICE:
                ···
                handleBindService((BindServiceData)msg.obj);
                ···
                break;
        ····
        }
    }
}

private void handleBindService(BindServiceData data) {
    Service s = mServices.get(data.token);
    ····
    if (s != null) {
        try {
            ····
            try {
                if (!data.rebind) {
                    //获取到服务自定义的Binder对象,也是调用onBind生命周期方法
                    IBinder binder = s.onBind(data.intent);
                    //调用AMS所在进程的publishService方法进一步处理
                    ActivityManager.getService().publishService(
                            data.token, data.intent, binder);
                } else {
                    //重复绑定时执行的方法,代表已经绑定过
                    //调用onRebind生命周期方法
                    s.onRebind(data.intent);
                    //调用AMS所在进程的serviceDoneExecuting方法移除ANR任务
                    ActivityManager.getService().serviceDoneExecuting(
                            data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
                }
            }
            ····
        } catch (Exception e) {
            ····
        }
    }
}
复制代码
d、AMS继续处理绑定服务内的Binder实现类流程

此过程的目的是将绑定的服务内部onBind方法自定义的Binder实现对象回传到应用进程ServiceConnection类的onServiceConnected方法中 frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public void publishService(IBinder token, Intent intent, IBinder service) {
    ····
    synchronized(this) {
        ····
        //service是绑定服务内部onBind方法自定义的Binder实现类
        //token是ActiveServices中创建的Binder实现类
        mServices.publishServiceLocked((ServiceRecord)token, intent, service);
    }
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
    ···
    try {
        ····
        if (r != null) {
            ····
            if (b != null && !b.received) {
               ····
                for (int conni = connections.size() - 1; conni >= 0; conni--) {
                    ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
                    for (int i=0; i<clist.size(); i++) {
                        ····
                        try {
                            //调用到应用层注册的IServiceConnection的binder实现对象
                            //IServiceConnection是在应用层的LoadedApk.java对象内部类ServiceDispatcher中的内部类InnerConnection实现的
                            //InnerConnection对象继承了IServiceConnection.Stub
                            c.conn.connected(r.name, service, false);
                        }
                        ····
                    }
                }
            }
            //移除ANR超时任务
            serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
        }
    }
    ····
}
复制代码
e、应用进程处理绑定服务内的Binder实现类流程

frameworks/base/core/java/android/app/LoadedApk.java

static final class ServiceDispatcher {
    //跨进程通信Binder实现类
    private static class InnerConnection extends IServiceConnection.Stub {

        ····

        //AMS所在的进程调用此方法把绑定服务内部onBind中实现的Binder对象回调到ServiceConnection注册者
        public void connected(ComponentName name, IBinder service, boolean dead)
                throws RemoteException {
            LoadedApk.ServiceDispatcher sd = mDispatcher.get();
            if (sd != null) {
                sd.connected(name, service, dead);
            }
        }
    }

    public void connected(ComponentName name, IBinder service, boolean dead) {
        //如果在应用绑定服务在bindService方法中有传Executor对象这个参数,那么mActivityExecutor就不为null
        if (mActivityExecutor != null) {
            mActivityExecutor.execute(new RunConnection(name, service, 0, dead));
        } else if (mActivityThread != null) {
            ///如果在应用绑定服务在bindService方法中没有传Executor对象这个参数,
            // 那么会通过mMainThread.getHandler()获取到ActivityThread中的H对象,此时mActivityThread不为null
            mActivityThread.post(new RunConnection(name, service, 0, dead));
        } else {
            //基本不会调用到这里
            doConnected(name, service, dead);
        }
    }

    //定义一个
    private final class RunConnection implements Runnable {
        ···
        public void run() {
            ···
            //调用此方法进一步处理
            doConnected(mName, mService, mDead);
            ····
        }
        ····
    }

    public void doConnected(ComponentName name, IBinder service, boolean dead) {
        ·····
        //mConnection对应ServiceConnection对象,最终通过onServiceConnected将绑定服务的内部Binder对象返回给注册者
        if (service != null) {
            mConnection.onServiceConnected(name, service);
        } else {
            // The binding machinery worked, but the remote returned null from onBind().
            mConnection.onNullBinding(name);
        }
    }
}
复制代码

(3)、异进程服务启动绑定流程

(1)和(2)可以知道,无论是启动服务还是绑定服务,最终是通过SystemServer进程中的ActiveServices对象的bringUpServiceLocked方法来执行,bringUpServiceLocked方法是进程判断与启动新进程的入口,当在应用的AndroidManifest.xml文件中Service设置为新进程执行,那么就会在bringUpServiceLocked方法中启动一个新的进程

a、SystemServer进程与Zygote进程通信流程

android应用层次的进程都是通过Zygote进程去卵化启动的,Service进程也是一样 frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
                                    boolean whileRestarting, boolean permissionsReviewRequired)
        throws TransactionTooLargeException {
    ····
    //启动一个新的进程
    if (app == null && !permissionsReviewRequired) {
        if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
                hostingRecord, ZYGOTE_POLICY_FLAG_EMPTY, false, isolated, false)) == null) {
            ·····
            return msg;
        }
        if (isolated) {
            r.isolatedProc = app;
        }
    }
    ····
    return null;
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

final ProcessRecord startProcessLocked(String processName,
                                       ApplicationInfo info, boolean knownToBeDead, int intentFlags,
                                       HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
                                       boolean isolated, boolean keepIfLarge) {
    //mProcessList是一个ProcessList对象
    return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
            hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
            keepIfLarge, null /* ABI override */, null /* entryPoint */,
            null /* entryPointArgs */, null /* crashHandler */);
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ProcessList.java

boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
                           int zygotePolicyFlags, boolean disableHiddenApiChecks, boolean disableTestApiChecks,
                           boolean mountExtStorageFull, String abiOverride) {
    ····
    //新进程启动的入口类,即是android.app.ActivityThread类的main方法
    final String entryPoint = "android.app.ActivityThread";
    return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
            runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, requiredAbi,
            instructionSet, invokeWith, startTime);
    ····
}

boolean startProcessLocked(HostingRecord hostingRecord, String entryPoint, ProcessRecord app,
                           int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal,
                           String seInfo, String requiredAbi, String instructionSet, String invokeWith,
                           long startTime) {
    ····
    final Process.ProcessStartResult startResult = startProcess(hostingRecord,
            entryPoint, app,
            uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo,
            requiredAbi, instructionSet, invokeWith, startTime);
    ····
}


private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
                                                ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags,
                                                int mountExternal, String seInfo, String requiredAbi, String instructionSet,
                                                String invokeWith, long startTime) {
    ····
    //SystemServer进程与Zygote进程通信是通过LocalSocket和LocalServerSocket进行通信,并非是Binder
    startResult = Process.start(entryPoint,
            app.processName, uid, uid, gids, runtimeFlags, mountExternal,
            app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
            app.info.dataDir, invokeWith, app.info.packageName, zygotePolicyFlags,
            isTopApp, app.mDisabledCompatChanges, pkgDataInfoMap,
            whitelistedAppDataInfoMap, bindMountAppsData, bindMountAppStorageDirs,
            new String[]{PROC_START_SEQ_IDENT + app.startSeq});
    ····
    return startResult;
    ····
}
复制代码

SystemServer进程与Zygote进程通信是通过LocalSocket和LocalServerSocket进行通信,并非是Binder,最终Zygote进程启动好新进程则会调用android.app.ActivityThread类的main方法,此时新进程启动完成

b、Zygote进程与新启动进程通信流程

新进程启动完会调用android.app.ActivityThread类的main方法 frameworks/base/core/java/android/app/ActivityThread.java

public static void main(String[] args) {
    ····
    Looper.prepareMainLooper();
    ····
    //创建一个ActivityThread,同时创建一个ApplicationThread的binder对象,用于跨进程通讯
    ActivityThread thread = new ActivityThread();
    //启动一个Application
    thread.attach(false, startSeq);
    ····
    Looper.loop();
   ····
}

private void attach(boolean system, long startSeq) {
    ····
    final IActivityManager mgr = ActivityManager.getService();
    try {
        //跨进程调用AMS的attachApplication方法
        mgr.attachApplication(mAppThread, startSeq);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
    ····
}
复制代码
c、新启动进程与SystemServer进程(AMS)通信流程

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public final void attachApplication(IApplicationThread thread, long startSeq) {
    ····
    synchronized (this) {
        ····
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        ····
    }
}

private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
                                        int pid, int callingUid, long startSeq) {
    ·····
    if (!badApp) {
        try {
            //启动服务,mServices为ActiveServices对象
            didSomething |= mServices.attachApplicationLocked(app, processName);
            ·····
        } catch (Exception e) {
            ·····
        }
    }
    ·····
    return true;
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

boolean attachApplicationLocked(ProcessRecord proc, String processName)
        throws RemoteException {
    ····
    //此时进程已经启动,启动服务
    realStartServiceLocked(sr, proc, sr.createdFromFg);
    ····
    return didSomething;
}
复制代码

realStartServiceLocked方法的执行源码流程,可以参考(1)和(2),realStartServiceLocked方法中主要是启动ANR超时任务监测,以及是启动服务还是绑定服务的生命周期调用分配,这样两种不同形式的服务独自执行各自的生命周期

(4)、服务启动超时(ANR)监测处理流程流程

Service生命周期的执行,最终通过ActiveServices对象的realStartServiceLocked方法去调配,此时也是加入了超时任务监测(ANR)

a、启动Server超时任务

frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

private final void realStartServiceLocked(ServiceRecord r,
                                          ProcessRecord app, boolean execInFg) throws RemoteException {
    ····
    //启动超时定时ANR任务
    bumpServiceExecutingLocked(r, execInFg, "create");
    //接下来就是启动Server一系列操作,或者计算在Server中的onCreate()生命周期方法是否有耗时操作
    ····
    try {
        ····
        //进入应用进程启动,移除超时定时ANR任务操作也在此处
        app.thread.scheduleCreateService(r, r.serviceInfo,
                mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
                app.getReportedProcState());
        ····
        //完成启动
        created = true;
    } catch (DeadObjectException e) {
        ····
    }
    ···
}

private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
    ····
    //开启超时任务
    scheduleServiceTimeoutLocked(r.app);
    ···
}

void scheduleServiceTimeoutLocked(ProcessRecord proc) {
    ····
    //通过Handler发送一个定时任务,当时间到没有移除这个任务,则认为是超时
    Message msg = mAm.mHandler.obtainMessage(
            ActivityManagerService.SERVICE_TIMEOUT_MSG);
    msg.obj = proc;
    mAm.mHandler.sendMessageDelayed(msg,
            proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

final class MainHandler extends Handler {
    ····
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            ····
            //当Server超时的时候,回调到此处,准备弹ANR窗口
            case SERVICE_TIMEOUT_MSG: {
                mServices.serviceTimeout((ProcessRecord)msg.obj);
            } break;
            ···
            //当内容提供者超时,回调到此处,准备弹ANR窗口
            case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
                ProcessRecord app = (ProcessRecord)msg.obj;
                synchronized (ActivityManagerService.this) {
                    processContentProviderPublishTimedOutLocked(app);
                }
            } break;
            ····
        }
    }
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

//前台server超时时间
static final int SERVICE_TIMEOUT = 20 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
//后台server超时时间
static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;

void serviceTimeout(ProcessRecord proc) {
    String anrMessage = null;
    synchronized(mAm) {
        ····
        if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) {
            ····
            //超时后来到此处anrMessage赋值
            anrMessage = "executing service " + timeout.shortInstanceName;
        } else {
            //初始化定时,设定超时时间
            Message msg = mAm.mHandler.obtainMessage(
                    ActivityManagerService.SERVICE_TIMEOUT_MSG);
            msg.obj = proc;
            mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
                    ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
        }
    }
    //当时间达到了server超时时间,则进入此处
    if (anrMessage != null) {
        //最终通过此处处理ANR
        mAm.mAnrHelper.appNotResponding(proc, anrMessage);
    }
}
复制代码

frameworks/base/services/core/java/com/android/server/am/AnrHelper.java

class AnrHelper {
    private static class AnrRecord {
        ····
        final ProcessRecord mApp;
        ····
        void appNotResponding(boolean onlyDumpSelf) {
            //通过一系列操作最终调用ProcessRecord对象的appNotResponding方法
            mApp.appNotResponding(mActivityShortComponentName, mAppInfo,
                    mParentShortComponentName, mParentProcess, mAboveSystem, mAnnotation,
                    onlyDumpSelf);
        }
    }
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ProcessRecord.java

void appNotResponding(String activityShortComponentName, ApplicationInfo aInfo,
                      String parentShortComponentName, WindowProcessController parentProcess,
                      boolean aboveSystem, String annotation, boolean onlyDumpSelf) {
    ····
    synchronized (mService) {
        ····
        //mService对应的是ActivityManagerService对象
        if (mService.mUiHandler != null) {
            // Bring up the infamous App Not Responding dialog
            Message msg = Message.obtain();
            msg.what = ActivityManagerService.SHOW_NOT_RESPONDING_UI_MSG;
            msg.obj = new AppNotRespondingDialog.Data(this, aInfo, aboveSystem);
            //向UiHandler发送一条数据
            mService.mUiHandler.sendMessage(msg);
        }
    }
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

final class UiHandler extends Handler {
    ···
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            ····
            case SHOW_NOT_RESPONDING_UI_MSG: {
                //同Handler机制回调到此处弹起ANR窗口
                mAppErrors.handleShowAnrUi(msg);
                ensureBootCompleted();
            } break;
            ·····
        }
    }
}
复制代码
b、移除Server超时任务

frameworks/base/core/java/android/app/ActivityThread.java

public final void scheduleCreateService(IBinder token,
                                        ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
    updateProcessState(processState, false);
    CreateServiceData s = new CreateServiceData();
    s.token = token;
    s.info = info;
    s.compatInfo = compatInfo;
    //向主线程发送一条消息
    sendMessage(H.CREATE_SERVICE, s);
}

class H extends Handler {
    public void handleMessage(Message msg) {
        ····
        switch (msg.what) {
            ····
            case CREATE_SERVICE:
                ····
                //主线程处理Server启动
                handleCreateService((CreateServiceData) msg.obj);
                ····
                break;
            ····
        }
    }
}

private void handleCreateService(CreateServiceData data) {
    ····
    try {
        ····
        service.attach(context, this, data.info.name, data.token, app,
                ActivityManager.getService());
        //调用Server生命周期方法
        service.onCreate();
        ···
        try {
            //调用AMS的serviceDoneExecuting方法移除Server超时监测任务
            ActivityManager.getService().serviceDoneExecuting(
                    data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    } catch (Exception e) {
        ····
    }
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
    synchronized(this) {
        //mServices对应的是ActiveServices对象,移除超时任务
        mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
    }
}
复制代码

frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
    ····
    if (r != null) {
        ····
        //移除超时任务
        serviceDoneExecutingLocked(r, inDestroying, inDestroying);
        ····
    }
    ···
}

private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
                                        boolean finishing) {
    ····
    if (r.executeNesting <= 0) {
        if (r.app != null) {
            ···
            if (r.app.executingServices.size() == 0) {
                ····
                //向MainHandler移除SERVICE_TIMEOUT_MSG的超时任务
                mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
            }
            ····
        }
        ····
    }
}
复制代码

2、service的生命周期,两种启动模式的区别

(1)、通过startService()方法来启动服务

生命周期:onCreate() -> onStart()或者onStartCommand() -> onDestroy()

onStart()方法是在android 4.1以上版本废弃,采用onStartCommand()方法代替,当服务已经启动时,调用startService()方法不会重复调用onCreate()方法(只有在启动时调用一次),但会调用onStart()或者onStartCommand()方法,这在SystemServer进程的ActiveServices的bringUpServiceLocked方法中有体现:
frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
                                    boolean whileRestarting, boolean permissionsReviewRequired)
        throws TransactionTooLargeException {
    //如果服务已经启动,则进入此判断
    if (r.app != null && r.app.thread != null) {
        sendServiceArgsLocked(r, execInFg, false);
        return null;
    }
    ····
}

private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
                                         boolean oomAdjusted) throws TransactionTooLargeException {
    ····
    //通过跨进程调用应用进程的ActivityThread的ApplicationThread中的scheduleServiceArgs启动服务
    //最终调用到应用服务的onStartCommand()方法
    r.app.thread.scheduleServiceArgs(r, slice);
    ····
}
复制代码

当不使用服务时,调用stopService()来关闭,此时会调用服务的onDestroy()方法

特点:

  • 服务运行与注册者无关联,注册者退出服务不会退出,除非调用stopService()方法
(2)、通过bindService()方法绑定服务

生命周期:onCreate() -> onBind() -> onUnbind() -> onDestroy()

当服务已经绑定,通过unbindService()解绑(没有最终调用spotService()退出服务情况下),此时onUnbind()返回true,再通过bindService()绑定服务,此时不会再调用onBind(),而是调用onRebind(),生命周期如下:

onCreate() -> onBind() -> 调用unbindService()解绑 -> onUnbind(true) -> 调用bindService()绑定 -> onRebind() -> onUnbind() -> onDestroy()

绑定的服务退出,绑定者退出或者调用unbindService()解绑退出

特点:

  • 绑定者可以通过服务内部自定义的Binder实现类来持有服务并且调用服务中的方法
  • 绑定者退出,那么服务也会跟着退出

3、service与activity怎么实现通信

1、通过Intent方式从Activity发送数据给Service
2、使用绑定服务的ServiceConnection通过Binder进行
3、内容提供者、存储的方式
4、广播
5、socket通信
6、全局静态变量方式
7、反射注入的方式(eventBus)

4、IntentService是什么?IntentService的原理?应用场景以及与service的区别

IntentService是一个可以执行耗时操作的服务,内部维护着HandlerThread封装的子线程消息队列来执行耗时任务,在任务执行完时调用stopSelf()方法自动退出服务

原理:
frameworks/base/core/java/android/app/IntentService.java

public abstract class IntentService extends Service {
    ····
    //定义一个Handler对象用于接收与发送消息
    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            //一个抽象方法,可以被继承者重写,运行在子线程消息队列中
            onHandleIntent((Intent)msg.obj);
            //任务执行完,自定关闭当前服务
            stopSelf(msg.arg1);
        }
    }
    ·····

    @Override
    public void onCreate() {
        super.onCreate();
        //创建一个HandlerThread对象,HandlerThread是子线程消息循环队列
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();
        mServiceLooper = thread.getLooper();
        //创建一个子线程的Handler对象,发送的消息运行在子线程消息队列中
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void onStart(@android.annotation.Nullable Intent intent, int startId) {
        //使用Handler向子线程消息循环队列发送一条消息
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }
    
    @Override
    public int onStartCommand(@android.annotation.Nullable Intent intent, int flags, int startId) {
        //发送消息运行在子线程消息队列中
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    //抽象方法,运行在子线程消息队列中
    protected abstract void onHandleIntent(@android.annotation.Nullable Intent intent);
}
复制代码

应用场景:

  • 后台耗时操作
  • 短暂的耗时服务,如下载资源等

IntentService与service区别:

  • service不能直接执行耗时任务否则会引起ANR,IntentService可以执行耗时任务
  • service启动后需要手动调用stopService()关闭服务,IntentService启动后在执行完任何后会自动关闭服务

5、Service的onStartCommand方法有几种返回值?各代表什么意思?

有四种返回值:

  • START_STICKY:当某个服务被系统杀死时(不是正常结束服务),如果返回值为START_STICKY,则系统会尝试重启该服务,并且调用服务的onStartCommand()方法,但是onStartCommand()方法的Intent参数为Null。

  • START_NOT_STICKY:当某个服务被系统杀死时,如果返回值为START_NOT_STICKY,则系统不会重启该服务。

  • START_REDELIVER_INTENT:当某个服务被系统杀死时,如果返回值为START_REDELIVER_INTENT,则系统会尝试重启该服务,并且调用服务的onStartCommand()方法,并且会创建之前启动服务时传入的Intent,即onStartCommand()方法的Intent参数不为Null。

  • START_STICKY_COMPATIBILITY:这是START_STICKY的兼容版本,不能保证onStartCommand()方法一定会被重新调用。

6、bindService和startService混合使用的生命周期以及怎么关闭?

  • 调用startService() 生命周期 : onCreate() -> onStart()或者onStartCommand() -> onDestroy()
    通过调用stopService()方法关闭服务

  • 调用bindService() 生命周期:onCreate() -> onBind() -> onUnbind() -> onDestroy()
    通过调用unbindService()方法关闭服务

  • 先调用startService()后再调用bindService() 生命周期:onCreate() -> onStart()或者onStartCommand() -> onBind() -> onUnbind() -> onDestroy()
    先调用stopService()再调用unbindService()关闭服务

  • 先调用bindService()后再调用startService() 生命周期:onCreate() -> onBind() -> onStart()或者onStartCommand() -> onUnbind() -> onDestroy()
    先调用unbindService()再调用stopService()关闭服务

  • 先调用bindService()后调用unbindService(),最后调用bindService() 生命周期:onCreate() -> onBind() -> 调用unbindService()解绑 -> onUnbind(true) -> 调用bindService()绑定 -> onRebind() -> onUnbind() -> onDestroy()
    通过调用unbindService()方法关闭服务

分类:
Android
标签: