bindService启动流程

article/2025/10/1 8:03:30

通过bindService启动的Service,会执行Service的onCreate、onBind、onUnbind、onDestroy方法,可以通过onBind方法返回的Binder对象和调用端进行通信,并且Service的生命周期和调用端同步。 如下是启动bindService的代码

var stu: Student? = null
val connection = object : ServiceConnection {override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {stu = Student.Stub.asInterface(p1)}override fun onServiceDisconnected(p0: ComponentName?) {}
}
val intent = Intent(this, Student::class.java)
bindService(intent, connection, BIND_AUTO_CREATE)复制代码

如下是bindService的启动流程:

1.bindService 发起端进程

1.1 ContextWrapper.bindService

public class ContextWrapper extends Context {public boolean bindService(Intent service, ServiceConnection conn,int flags) {//mBase为ContentImplreturn mBase.bindService(service, conn, flags);}
}
复制代码

继续调用ContentImpl.bindService方法:

class ContextImpl extends Context {public boolean bindService(Intent service, ServiceConnection conn, int flags) {warnIfCallingFromSystemProcess();return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,getUser());}final @NonNull LoadedApk mPackageInfo;private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,String instanceName, Handler handler, Executor executor, UserHandle user) {// 将ServiceConnection转换成Binder对象变量,用于进程间通信IServiceConnection sd;//...if (mPackageInfo != null) {// 将ServiceConnection转换成可跨进程if (executor != null) {sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);} else {sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);}} else {throw new RuntimeException("Not supported in system context");}validateServiceIntent(service);try {//...// 调用AMS.bindIsolatedService方法int res = ActivityManager.getService().bindIsolatedService(mMainThread.getApplicationThread(), getActivityToken(), service,service.resolveTypeIfNeeded(getContentResolver()),sd, flags, instanceName, getOpPackageName(), user.getIdentifier());if (res < 0) {throw new SecurityException("Not allowed to bind to service " + service);}return res != 0;} catch (RemoteException e) {throw e.rethrowFromSystemServer();}}
}
复制代码

首先将ServiceConnection变量存储到可跨进程通信的Binder对象并赋值到sd变量,并把sd变量传给AMS中,后续AMS通过这个Binder通信。最后调用AMS.bindIsolatedService跨进程调用方法。在分析另一个AMS进程前,先分析本进程如何

public final class LoadedApk {@UnsupportedAppUsagepublic final IServiceConnection getServiceDispatcher(ServiceConnection c,Context context, Handler handler, int flags) {return getServiceDispatcherCommon(c, context, handler, null, flags);}private IServiceConnection getServiceDispatcherCommon(ServiceConnection c,Context context, Handler handler, Executor executor, int flags) {synchronized (mServices) {LoadedApk.ServiceDispatcher sd = null;//...// 创建ServiceDispatcher对象,并把ServiceConnection参数作为其变量之一sd = new ServiceDispatcher(c, context, executor, flags);//...// 返回ServiceDispatcher.InnerConnection内部类,其继承IServiceConnection.Stub,是个binderreturn sd.getIServiceConnection();}}
}static final class ServiceDispatcher {// 返回的是此对象private final ServiceDispatcher.InnerConnection mIServiceConnection;// 存储ServiceConnection的变量private final ServiceConnection mConnection;private final Context mContext;private final Handler mActivityThread;private final Executor mActivityExecutor;private final ServiceConnectionLeaked mLocation;ServiceDispatcher(ServiceConnection conn,Context context, Handler activityThread, int flags) {//创建InnerConnection对象,等会会返回该对象mIServiceConnection = new InnerConnection(this);//用户定义的ServiceConnectionmConnection = conn;mContext = context;mActivityThread = activityThread;mActivityExecutor = null;mLocation = new ServiceConnectionLeaked(null);mLocation.fillInStackTrace();mFlags = flags;}// 返回的是mIServiceConnection变量,是Binder类IServiceConnection getIServiceConnection() {return mIServiceConnection;}//内部的Binder类private static class InnerConnection extends IServiceConnection.Stub {final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;// 通过构造函数弱引用ServiceDispatcher对象,此对象有ServiceConnection变量InnerConnection(LoadedApk.ServiceDispatcher sd) {mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);}// 调用ServiceDispatcher.connected()方法public void connected(ComponentName name, IBinder service, boolean dead)throws RemoteException {LoadedApk.ServiceDispatcher sd = mDispatcher.get();if (sd != null) {sd.connected(name, service, dead);}}}// ServiceDispatcher.connected()的方法public void connected(ComponentName name, IBinder service, boolean dead) {if (mActivityExecutor != null) {// 在线程池执行一个任务mActivityExecutor.execute(new RunConnection(name, service, 0, dead));} else if (mActivityThread != null) {// 给主线程发送一个post一个任务mActivityThread.post(new RunConnection(name, service, 0, dead));} else {// 如果上述两个都为空,则执行doConnected方法doConnected(name, service, dead);}}private final class RunConnection implements Runnable {RunConnection(ComponentName name, IBinder service, int command, boolean dead) {mName = name;mService = service;mCommand = command;mDead = dead;}public void run() {if (mCommand == 0) {// mCommand为0 ,进入doConnected方法doConnected(mName, mService, mDead);} else if (mCommand == 1) {doDeath(mName, mService);}}final ComponentName mName;final IBinder mService;final int mCommand;final boolean mDead;}// 调用ServiceConnection.onServiceConnected()方法public void doConnected(ComponentName name, IBinder service, boolean dead) {ServiceDispatcher.ConnectionInfo old;ServiceDispatcher.ConnectionInfo info;synchronized (this) {if (mForgotten) {return;}old = mActiveConnections.get(name);if (old != null && old.binder == service) {return;}if (service != null) {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) {mActiveConnections.remove(name);return;}} else {mActiveConnections.remove(name);}if (old != null) {old.binder.unlinkToDeath(old.deathMonitor, 0);}}// 如果有旧服务,它现在已断开连接。if (old != null) {mConnection.onServiceDisconnected(name);}if (dead) {mConnection.onBindingDied(name);}//如果有新的可行服务,它现在已连接。if (service != null) {// 回调用户定义的ServiceConnection()mConnection.onServiceConnected(name, service);} else {// The binding machinery worked, but the remote returned null from onBind().mConnection.onNullBinding(name);}}}
复制代码

创建LoadedApk.ServiceDispatcher类的实例化对象,对象里面包含了一个Binder对象LoadedApk.ServiceDispatcher.InnerConnection,方法最后就是返回这个Binder对象。AMS也通过这个Binder对象通信调用ServiceConnection.onServiceConnected()方法。

 


http://chatgpt.dhexx.cn/article/rGV9d8PQ.shtml

相关文章

AIDL报错,bindService一直连接不上、不起作用。

先说问题&#xff0c;最近用aidl&#xff0c;发现bindService根本就不走&#xff0c;不知道咋回事&#xff0c;明明写的没有任何毛病啊&#xff1f; //aidl绑定private void bind() {Intent intent new Intent();String pkg "com.example.mzz_service";//需要调用…

服务两种启动方式(startService与bindService)的区别

综上两篇文章 1.Android Service的基本用法&#xff08;startService启动方式生命周期&#xff09; 2.Android Service与Activity之间的通信&#xff08;bindService启动方式&#xff09; 区别如下&#xff1a; 一.生命周期上的区别 startService启动服务&#xff1a;Service会…

进程间通讯:Binder:bindService之 onServiceConnected回调

1&#xff1a;bindService官方概述 很明显 通过Google官方文档描述&#xff0c;我们知道 1&#xff1a;bindService&#xff08;&#xff09;的返回值只是表明服务是否存在&#xff1b; 2&#xff1a;真正能代表是否成功绑定服务的是触发onServiceConnected&#xff08;&…

Android入门第41天-Android中的Service(bindService)

介绍 在前一天我们介绍了Android中有两种启动Service的方法。并擅述了startService和bindService的区别。同时我们着重讲了startService。 因此今天我们就来讲bindService。bindService大家可以认为它是和Android的一个共生体。即这个service所属的activity如果消亡那么bindS…

Android Binder框架实现之bindService详解

Android Binder框架实现之bindService详解 Android Binder框架实现目录&#xff1a; Android Binder框架实现之Binder的设计思想 Android Binder框架实现之何为匿名/实名Binder Android Binder框架实现之Binder中的数据结构 Android Binder框架实现之Binder相关的接口和类 Andr…

Android bindService流程

一. 前言 我们可以通过startService来启动一个服务, 当然也可以通过bindService绑定一个服务,本篇文章我们来讲一讲绑定服务的完整流程, 阅读此文之前,建议先阅读一下笔者的这三篇文章 Android 进程间通信机制(三) 系统进程与应用进程通信 Android 进程间通信机制(四) 应用进程…

bind服务程序

一、介绍 1、bind服务是全球范围内使用最广泛、最安全可靠且高效的域名解析服务程序。 2、为了有效地限制bind服务程序仅能对自身的配置文件进行操作&#xff0c;以确保整个服务器的安全&#xff0c;在安装部署bind服务程序时加上chroot&#xff08;俗称牢笼机制&#xff09;…

startService bindService 区别

Android执行Service有两种方法&#xff0c;一种是startService&#xff0c;一种是bindService。下面让我们一起来聊一聊这两种执行Service方法的区别。 1、生命周期上的区别 执行startService时&#xff0c;Service会经历onCreate->onStartCommand。当执行stopService时&…

Android中Service使用bindService

前面已经对Service的startServer方式启动一个服务了解过了&#xff0c;现在来看一下Service的另一种启动方式→bindServer bindServer使用场景 1、在同个app之间调用&#xff08;即是同一个进程中&#xff09; 2、在不同app之间调用&#xff08;即是跨进程间通信&#xff09…

Android——bindService()方法启动服务

通过绑定服务来启动的话需要注意创建一个类来实现ServiceConnection接口&#xff0c;重写onServiceConnected&#xff08;&#xff09;和onServiceDisconnected&#xff08;&#xff09;方法。这个类用于服务的连接。成功绑定服务时&#xff0c;会调用onServiceConnected&#…

Android Service 服务(三)—— bindService与remoteService

一、bindService简介 bindService是绑定Service服务&#xff0c;执行service服务中的逻辑流程。 service通过Context.startService()方法开始&#xff0c;通过Context.stopService()方法停止&#xff1b;也可以通过Service.stopSelf()方法或者Service.stopSelfResult()方法来停…

SO_BINDTODEVICE 使用

就绑定到了接口"lmi40"上,所有数据报的收发都只经过这个网卡. 对于SOL_BINDTODEVICE的总结如下: &#xff08;1&#xff09; 对于TCP套接口、UDP套接口、RAW套接口&#xff0c;可以通过SO_BINDTODEVICE套接口选项将套接口绑定到指定的网络接口上。绑定之后&…

startService与bindService的区别

Android执行Service有两种方法&#xff0c;一种是startService&#xff0c;一种是bindService。下面让我们一起来聊一聊这两种执行Service方法的区别。 1、生命周期上的区别 执行startService时&#xff0c;Service会经历onCreate->onStartCommand。当执行stopService时&…

startService和bindService的区别

首先看下其生命周期的区别&#xff1a; 生命周期&#xff1a; onCreate → startCommand → onDestroy onCreate → onBind→onUnBind→ onDestroy 静态绑定对应着startService&#xff1b;动态绑定对应着bindService&#xff0c;静态有自己独立的生命周期&#xff0c;动态会…

bindService的使用

bindService与starService之间的区别&#xff1a; 在程序通过startService&#xff08;&#xff09;方法启动的服务&#xff0c;会长期在后台运行&#xff0c;并且启动服务的组件与服务之间没有关系&#xff0c;即使启动服务的组件被销毁&#xff0c;服务还是会运行。 但是当一…

Service学习以及BindService的使用

Service 什么是Service Service是一个可以在后台执行长时间操作而不使用用户界面的应用组件。 如何使用Service 我们首先需要实现一个Service的子类。主要实现Service的onCreat&#xff08;&#xff09;&#xff0c;onStartCommand&#xff08;&#xff09;&#xff0c;onB…

Android中bindService的使用及Service生命周期

Android中有两种主要方式使用Service&#xff0c;通过调用Context的startService方法或调用Context的bindService方法&#xff0c;本文只探讨纯bindService的使用&#xff0c;不涉及任何startService方法调用的情况。如果想了解startService相关的使用&#xff0c;请参见《Andr…

粒子群算法笔记

实质&#xff1a;在定义域随机放置多个变量&#xff0c;不断跳跃&#xff0c;同步寻找最优解。寻找方向受单个粒子与全部粒子的最优位置共同影响。单个粒子按照公式不断迭代寻找当新位置。多个变量聚集在某一点时&#xff0c;该点即是最优解。 控制其搜索速度&#xff08;步长…

粒子群算法及C++实现

参考博客 https://www.cnblogs.com/alan666/p/8311804.html https://blog.csdn.net/weixin_39059031/article/details/103723843 https://blog.csdn.net/weixin_40679412/article/details/80571854 https://blog.csdn.net/daaikuaichuan/article/details/81382794 https://blo…

粒子群算法详解

一.产生背景 ❃粒子群算法(particleswarm optimization&#xff0c;PSO)由Kennedy和Eberhart在1995年提出&#xff0c;该算法对于Hepper的模拟鸟群(鱼群)的模型进行修正&#xff0c;以使粒子能够飞向解空间&#xff0c;并在最好解处降落&#xff0c;从而得到了粒子群优化算法。…