Android中Service使用bindService

article/2025/10/1 8:17:11

前面已经对Service的startServer方式启动一个服务了解过了,现在来看一下Service的另一种启动方式→bindServer

bindServer使用场景

1、在同个app之间调用(即是同一个进程中)

2、在不同app之间调用(即是跨进程间通信)


同个app间调用(只有一次启动该服务)

BinderActicityA

public class BinderActicityA extends Activity implements View.OnClickListener {private Button btn1;private Button btn2;private Button btn3;private Button btn4;private BindService bindService = null;private boolean isBound = false;private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {isBound = true;BindService.MyBinder binder = (BindService.MyBinder) service;bindService = binder.getService();int num = bindService.getRandomNumber();Log.v("hjz","numA="+num);}//client 和service连接意外丢失时,会调用该方法@Overridepublic void onServiceDisconnected(ComponentName name) {Log.v("hjz","onServiceDisconnected  A");}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_binder_main);findLayoutView();setLister();initData();}private void findLayoutView() {btn1 = (Button) findViewById(R.id.btn1);btn2 = (Button) findViewById(R.id.btn2);btn3 = (Button) findViewById(R.id.btn3);btn4 = (Button) findViewById(R.id.btn4);}private void setLister() {btn1.setOnClickListener(this);btn2.setOnClickListener(this);btn3.setOnClickListener(this);btn4.setOnClickListener(this);}private void initData() {}@Overridepublic void onClick(View v) {Intent intent = null;switch (v.getId()){case R.id.btn1:intent = new Intent(BinderActicityA.this, BindService.class);intent.putExtra("from", "ActivityA");bindService(intent,conn,BIND_AUTO_CREATE);break;case R.id.btn2:if (isBound){isBound = false;Log.v("hjz","ActicityA is unbindService");unbindService(conn);}break;case R.id.btn3:intent = new Intent(this, BinderActivityB.class);startActivity(intent);break;case R.id.btn4:this.finish();break;}}@Overrideprotected void onDestroy() {super.onDestroy();Log.i("hjz", "ActivityA -> onDestroy");}
}


xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:orientation="vertical"tools:context="com.hh.servicedemo.MainActivity"><Buttonandroid:id="@+id/btn1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="BinderService绑定"/><Buttonandroid:id="@+id/btn2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="BinderService解绑"/><Buttonandroid:id="@+id/btn3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="跳转到BinderActivityB"/><Buttonandroid:id="@+id/btn4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="finish"/></LinearLayout>


BinderService

public class BindService extends Service {public class MyBinder extends Binder{public BindService getService(){return BindService.this;}}//通过binder实现了 调用者(client)与 service之间的通信private MyBinder binder = new MyBinder();private final Random generator = new Random();@Overridepublic void onCreate() {super.onCreate();Log.i("hjz","BindService -> onCreate, Thread: " + Thread.currentThread().getName());}@Overridepublic IBinder onBind(Intent intent) {Log.i("hjz", "BindService -> onBind, Thread: " + Thread.currentThread().getName());return binder;}@Overridepublic boolean onUnbind(Intent intent) {Log.i("hjz", "BindService -> onUnbind, from:" + intent.getStringExtra("from"));return false;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i("hjz", "BindService -> onStartCommand, startId: " + startId + ", Thread: " + Thread.currentThread().getName());return START_NOT_STICKY;}@Overridepublic void onDestroy() {Log.i("hjz", "BindService -> onDestroy, Thread: " + Thread.currentThread().getName());super.onDestroy();}//在Service中暴露出去的方法,供client调用public int getRandomNumber(){return generator.nextInt();}
}

点击BinderService绑定,再点击BinderService解绑,最后点击finish,打印日志

07-09 11:46:49.360 29714-29714/com.hh.servicedemo I/hjz: BindService -> onCreate, Thread: main
07-09 11:46:49.360 29714-29714/com.hh.servicedemo I/hjz: BindService -> onBind, Thread: main
07-09 11:46:49.380 29714-29714/com.hh.servicedemo V/hjz: numA=1859239539
07-09 11:46:50.650 29714-29714/com.hh.servicedemo V/hjz: ActicityA is unbindService
07-09 11:46:50.650 29714-29714/com.hh.servicedemo I/hjz: BindService -> onUnbind, from:ActivityA
07-09 11:46:50.650 29714-29714/com.hh.servicedemo I/hjz: BindService -> onDestroy, Thread: main
07-09 11:46:52.290 29714-29714/com.hh.servicedemo I/hjz: ActivityA -> onDestroy

点击BinderService绑定,再点击finish

07-09 11:48:07.260 29714-29714/com.hh.servicedemo I/hjz: BindService -> onCreate, Thread: main
07-09 11:48:07.260 29714-29714/com.hh.servicedemo I/hjz: BindService -> onBind, Thread: main
07-09 11:48:07.270 29714-29714/com.hh.servicedemo V/hjz: numA=-341510490
07-09 11:48:09.290 29714-29714/com.hh.servicedemo I/hjz: ActivityA -> onDestroy
07-09 11:48:09.310 29714-29714/com.hh.servicedemo I/hjz: BindService -> onUnbind, from:ActivityA
07-09 11:48:09.310 29714-29714/com.hh.servicedemo I/hjz: BindService -> onDestroy, Thread: main


先从BinderService来分析,从打印可以看出,先调用onCreate,接着在调用onBind方法,你会发现使用binderStart来启动,onStartCommand这方法不调用;在Service中执行顺序:

1、先得到相应的binder对象,可以在Service内部用内部类得到相应的binder,如下所示:

 public class MyBinder extends Binder{public BindService getService(){return BindService.this;}}//通过binder实现了 调用者(client)与 service之间的通信private MyBinder binder = new MyBinder();
2、在onBind方法中返回IBinder实例,返回实例可以是Service实例本身 或者 通过binder暴露出Service公共方法。通常情况下,就是讲binder弄成Service内部类,然后在binder中创建一个类似getService的方法并返回包含binder的Service对象,如上面那种情况,这样client(客户端)可以通过该方法得到相应的Service实例


接着 调用者(client客户端)执行的流程

1、先创建ServiceConnetion实例,并重写其方法,如下面所示:

//创建ServiceConnection类型的实例private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {isBound = true;BindService.MyBinder binder = (BindService.MyBinder) service;bindService = binder.getService();int num = bindService.getRandomNumber();Log.v("hjz","numA="+num);}//client 和service连接意外丢失时,会调用该方法@Overridepublic void onServiceDisconnected(ComponentName name) {Log.v("hjz","onServiceDisconnected  A");}};
这是因为使用bindServer中使用到该对象,bindServer源码

@Overridepublic boolean bindService(Intent service, ServiceConnection conn,int flags) {//调用bindServer,发现第二个传参就是ServiceConnection对象return mBase.bindService(service, conn, flags);}

2、当执行了onServiceConnected回调时,我们可以通过IBinder实例得到Service实例对象 或 直接调用binder公共方法,这样就实现了client和service的连接

3、client和Service解除绑定时,onServiceDisconnected并不会被调用;onServiceDisconnected被调用的情况是发生在client和Service连接意外丢失时,这时client和Service一定是断开连接了。


同个app间调用(多次调用该服务)

BinderAcivityB

public class BinderActivityB extends Activity implements View.OnClickListener {private Button btn1;private Button btn2;private Button btn4;private BindService bindService = null;private boolean isBound = false;private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {isBound = true;BindService.MyBinder binder = (BindService.MyBinder) service;bindService = binder.getService();int num = bindService.getRandomNumber();Log.v("hjz","numB="+num);}@Overridepublic void onServiceDisconnected(ComponentName name) {Log.v("hjz","onServiceDisconnected  B");}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_binder_b);findLayoutView();setLister();initData();}private void findLayoutView() {btn1 = (Button) findViewById(R.id.btn1);btn2 = (Button) findViewById(R.id.btn2);btn4 = (Button) findViewById(R.id.btn4);}private void setLister() {btn1.setOnClickListener(this);btn2.setOnClickListener(this);btn4.setOnClickListener(this);}private void initData() {}@Overridepublic void onClick(View v) {Intent intent = null;switch (v.getId()){case R.id.btn1:intent = new Intent(BinderActivityB.this, BindService.class);intent.putExtra("from", "ActivityB");bindService(intent,conn,BIND_AUTO_CREATE);break;case R.id.btn2:if (isBound){isBound = false;Log.v("hjz","ActicityB is unbindService");unbindService(conn);}break;case R.id.btn4:this.finish();break;}}@Overrideprotected void onDestroy() {super.onDestroy();Log.i("hjz", "ActivityB -> onDestroy");}
}
在binderA中, 点击 binderA绑定→跳转BinderAcitivityB→binderB绑定→binderB解绑→BinderB finish→BinderA解绑→BinderA finish 的日志

07-09 13:16:10.030 8593-8593/com.hh.servicedemo I/hjz: BindService -> onCreate, Thread: main
07-09 13:16:10.030 8593-8593/com.hh.servicedemo I/hjz: BindService -> onBind, Thread: main
07-09 13:16:10.050 8593-8593/com.hh.servicedemo V/hjz: numA=665064614
07-09 13:16:13.650 8593-8593/com.hh.servicedemo V/hjz: numB=1116469133
07-09 13:16:16.550 8593-8593/com.hh.servicedemo V/hjz: ActicityB is unbindService
07-09 13:16:18.680 8593-8593/com.hh.servicedemo I/hjz: ActivityB -> onDestroy
07-09 13:16:22.920 8593-8593/com.hh.servicedemo V/hjz: ActicityA is unbindService
07-09 13:16:22.930 8593-8593/com.hh.servicedemo I/hjz: BindService -> onUnbind, from:ActivityA
07-09 13:16:22.950 8593-8593/com.hh.servicedemo I/hjz: BindService -> onDestroy, Thread: main
07-09 13:16:25.660 8593-8593/com.hh.servicedemo I/hjz: ActivityA -> onDestroy

从打印日志中发现

在client(客户端)调用Service【同一个Service】情况下:

如果Service不存在,Service执行顺序是onCreate→onBind,接着client创建ServiceConnection实例并执行onServiceConnected这个方法。

如果Service已处于运行状态【说明在此之前已经在其他地方启动过该Service】,由于之前执行过的onBind回调获取IBinder实例,该IBinder实例在所有的client(客户端)之间是共享的,所以第二次执行onBind回调,直接使用上次已经获取的IBinder实例,并将其传入到与之对应的onServiceConnected方法中,标志着连接已经建立了起来,这时就有两个或者多个client(客户端)和Service绑定了。

client(客户端)执行unbindServie的流程:

client与Service解除绑定时,Service先检测是否还与其他client(客户端)与其连接→

如果没有,Service执行onUnbind方法,然后在执行onDestroy方法

如果有,Service不会执行onUnbind和onDestroy方法(从打印的日志中可以得出这样结论)


点击 binderA绑定→跳转BinderAcitivityB→binderB绑定→binderB解绑→BinderB finish→BinderA finish 的日志

07-09 13:19:58.340 8297-8297/com.hh.servicedemo I/hjz: BindService -> onCreate, Thread: main
07-09 13:19:58.360 8297-8297/com.hh.servicedemo I/hjz: BindService -> onBind, Thread: main
07-09 13:19:58.360 8297-8297/com.hh.servicedemo V/hjz: numA=2026321547
07-09 13:20:02.190 8297-8297/com.hh.servicedemo V/hjz: numB=-1586530569
07-09 13:20:04.140 8297-8297/com.hh.servicedemo V/hjz: ActicityB is unbindService
07-09 13:20:05.820 8297-8297/com.hh.servicedemo I/hjz: ActivityB -> onDestroy
07-09 13:20:07.080 8297-8297/com.hh.servicedemo I/hjz: ActivityA -> onDestroy
07-09 13:20:07.110 8297-8297/com.hh.servicedemo I/hjz: BindService -> onUnbind, from:ActivityA
07-09 13:20:07.110 8297-8297/com.hh.servicedemo I/hjz: BindService -> onDestroy, Thread: main

结论:当client与Service通过bindServer连接起来之后,如果client(客户端)执行(onDestroy)销毁,那么client会自动与Service解除绑定。

点击 binderA绑定→跳转BinderAcitivityB→binderB绑定→BinderB finish→BinderA解绑→BinderA finish 的日志
07-09 13:17:40.320 8297-8297/com.hh.servicedemo I/hjz: BindService -> onCreate, Thread: main
07-09 13:17:40.320 8297-8297/com.hh.servicedemo I/hjz: BindService -> onBind, Thread: main
07-09 13:17:40.340 8297-8297/com.hh.servicedemo V/hjz: numA=-1117645606
07-09 13:17:43.460 8297-8297/com.hh.servicedemo V/hjz: numB=1774346322
07-09 13:17:44.770 8297-8297/com.hh.servicedemo I/hjz: ActivityB -> onDestroy
07-09 13:17:56.780 8297-8297/com.hh.servicedemo V/hjz: ActicityA is unbindService
07-09 13:17:56.780 8297-8297/com.hh.servicedemo I/hjz: BindService -> onUnbind, from:ActivityA
07-09 13:17:56.780 8297-8297/com.hh.servicedemo I/hjz: BindService -> onDestroy, Thread: main
07-09 13:17:58.060 8297-8297/com.hh.servicedemo I/hjz: ActivityA -> onDestroy

点击 binderA绑定→跳转BinderAcitivityB→binderB绑定→BinderB finish→BinderA finish 的日志

07-09 13:21:22.890 8297-8297/com.hh.servicedemo I/hjz: BindService -> onCreate, Thread: main
07-09 13:21:22.890 8297-8297/com.hh.servicedemo I/hjz: BindService -> onBind, Thread: main
07-09 13:21:22.900 8297-8297/com.hh.servicedemo V/hjz: numA=1947324308
07-09 13:21:26.630 8297-8297/com.hh.servicedemo V/hjz: numB=-1343649013
07-09 13:21:27.730 8297-8297/com.hh.servicedemo I/hjz: ActivityB -> onDestroy
07-09 13:21:29.040 8297-8297/com.hh.servicedemo I/hjz: ActivityA -> onDestroy
07-09 13:21:29.060 8297-8297/com.hh.servicedemo I/hjz: BindService -> onUnbind, from:ActivityA
07-09 13:21:29.060 8297-8297/com.hh.servicedemo I/hjz: BindService -> onDestroy, Thread: main

上面的日志打印,下面用一张图来总结一下client和Service操作流程:



在不同app之间调用这里就不做介绍了,有兴趣的自己可以去研究一下



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

相关文章

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;从而得到了粒子群优化算法。…

高铁列车粒子群算法及改进粒子群算法多目标单目标运行优化设计

问题介绍 根据表1、2、3 所列数据&#xff0c;以能耗、运行时间、舒适性为目标分别设计列车运行速度—距离曲线&#xff1b;完成单目标以及多目标优化下的列车运行对比&#xff1b;选择其中一种方案&#xff0c;设计列车速度跟踪控制算法并进行性能分析。 1 列车参数设置表优化…

智能优化算法之粒子群算法

1、粒子群优化算法概述 粒子群优化算法(PSO&#xff1a;Particle swarm optimization) 是一种进化计算技术&#xff08;evolutionary computation&#xff09;。源于对鸟群捕食的行为研究。粒子群优化算法的基本思想&#xff1a;是通过群体中个体之间的协作和信息共享来寻找最优…

基于群智能的三维路径规划算法 2 —— 粒子群算法

目录 1 PSO算法的基本理论2 PSO算法程序设计流程3 MATLAB编程实现4 算法举例5 函数1 unifrnd函数 1 PSO算法的基本理论 将三个散点看做一个粒子 惯性分量就是 v i − 1 d v^d_{i-1} vi−1d​ 粒子群&#xff08;PSO&#xff09;算法是依托群鸟觅食的模型寻找最优解。群体特征…

粒子群算法(2)

上一期&#xff1a;粒子群算法&#xff08;1&#xff09; 线性递减惯性权重 惯性权重w体现的是粒子继承先前的速度的能力&#xff0c;Shi,Y最先将惯性权重w引入到粒子群算法中&#xff0c;并分析指出一个较大的惯性权值有利于全局搜索&#xff0c;而一个较小的权值则更利于局部…

粒子群算法简介

粒子群算法简介 前言 本文内容借鉴于 刘衍民的博士论文:“粒子群算法的研究及应用”. 现有的大多数群智能算法,如:乌鸦算法、鸽子算法、蚁群算法、萤火虫算法和灰狼优化算法等&#xff0c;都可以归类为粒子群算法.(个人觉得,这些算法就是整个稀奇古怪的名字,颇有舞文弄墨,强…

粒子群算法(1)

粒子群算法 1.入门 粒子群算法&#xff0c;其全称为粒子群优化算法(Particle Swarm Optimization,PsO)。它是通过模拟鸟群觅食行为而发展起来的一种基于群体协作的搜索算法。 2.什么是启发式算法&#xff1f; 启发式算法百度百科上的定义:一个基于直观或经验构造的算法,在可…

粒子群优化算法

背景 1995 年&#xff0c;Kennedy 和 Eberhart 两位博士共同 提出了粒子群优化算法 (Particle swarm optimization&#xff0c; PSO) PSO 算法中&#xff0c;将鸟群的个体位置或食物当作优化问题的解&#xff0c;利用群体中个体与最优个体以及个体之间的信息交互&#xff0c;引…

粒子群算法

粒子群算法简介 粒子群算法&#xff0c;其全称为粒子群优化算法(Particle Swarm Optimization,PSO) 。它是通过模拟鸟群觅食行为而发展起来的一种基于群体协作的搜索算法。粒子群算法属于启发式算法也叫智能优化算法&#xff0c;其基本思想在于通过群体中个体之间的协作和信息…

粒子群(PSO)算法的理解与应用

最近在学习粒子群算法&#xff0c;看了很多资料都有点摸不清头脑&#xff0c;直到看了一篇博客中超级简洁的粒子群C实现代码&#xff0c;才明白粒子群算法的原理&#xff0c;真心感谢博主&#xff0c;在此贴出博主的博客地址&#xff1a; http://blog.sina.com.cn/s/blog_4ed02…