当前位置: 首页 > news >正文

Android Service的生命周期,两种启动方法,有什么区别

Android Service的生命周期,两种启动方法,有什么区别

Android Service是一种后台组件,用于在后台执行长时间运行的任务,而无需与用户界面进行交互。Service具有自己的生命周期,其主要包含以下几个状态:创建(Created)、启动(Started)、绑定(Bound)和销毁(Destroyed)。现在,让我详细展开Android Service的生命周期和两种启动方法以及它们之间的区别:

Android Service的生命周期:

  • 创建(Created):
    在调用onCreate()方法后,Service会进入Created状态。在这个阶段,Service被创建并初始化,但尚未开始运行。

  • 启动(Started):
    当调用onStartCommand()方法后,Service会进入Started状态。在这个阶段,Service已经开始运行,并且会在后台执行耗时任务。Service将一直运行直到调用stopSelf()或者其他组件通过调用stopService()停止该Service。

  • 绑定(Bound):
    Service可以通过bindService()方法绑定到其他组件(例如Activity)上。当Service被绑定后,与之绑定的组件可以与Service进行通信,并调用Service中的方法。在这个阶段,Service仍然在运行,但可以通过调用unbindService()解除绑定。

  • 销毁(Destroyed):
    当Service不再被使用并且没有被绑定时,系统会调用onDestroy()方法,将Service销毁并释放资源。

两种启动方法及区别:

启动Service(Started Service):

  • 使用startService(Intent intent)方法启动Service。
  • Service会一直运行直到调用stopSelf()或者其他组件通过stopService()停止该Service。
  • 不需要与调用者进行绑定,Service可以在后台执行耗时任务。

绑定Service(Bound Service):

  • 使用bindService(Intent intent, ServiceConnection connection, int flags)方法绑定Service。
  • Service和调用者之间建立了绑定关系,调用者可以通过ServiceConnection与Service进行通信。
  • 当所有与之绑定的组件都解除绑定时,系统会销毁Service。

区别:

  • 启动Service适用于执行后台任务,即使调用者退出,Service仍然会继续运行。
  • 绑定Service适用于需要与其他组件进行交互的情况,Service的生命周期由绑定的组件决定。

需要注意的是,绝大多数情况下,Service都应该在后台线程中执行耗时任务,以免阻塞主线程,从而导致应用程序无响应。

代码举例说明

让我们通过代码来演示Android Service的两种启动方法:Started Service和Bound Service。

  • 创建一个继承自Service的Started Service类,例如MyStartedService。
public class MyStartedService extends Service {@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// 在这里执行后台任务,例如下载文件等耗时操作// 注意:不要在主线程执行耗时任务,以免阻塞应用程序// ...// 任务执行完成后,调用stopSelf()停止ServicestopSelf();// 返回START_NOT_STICKY,表示Service在被异常杀死后不会自动重启return START_NOT_STICKY;}@Nullable@Overridepublic IBinder onBind(Intent intent) {// Started Service不支持绑定,所以该方法返回nullreturn null;}
}
  • 在AndroidManifest.xml文件中注册Started Service:
<serviceandroid:name=".MyStartedService"android:enabled="true"android:exported="false" />
  • 在其他组件(例如Activity)中启动Started Service:
Intent serviceIntent = new Intent(this, MyStartedService.class);
startService(serviceIntent);

Bound Service 示例:

  • 创建一个继承自Service的Bound Service类,例如MyBoundService。
public class MyBoundService extends Service {private final IBinder binder = new MyBinder();public class MyBinder extends Binder {MyBoundService getService() {return MyBoundService.this;}}@Nullable@Overridepublic IBinder onBind(Intent intent) {// 返回Binder对象,允许调用者与Service进行通信return binder;}// 在Bound Service中可以提供一些公共方法供调用者调用public void doSomething() {// 在这里执行一些操作}
}
  • 在AndroidManifest.xml文件中注册Bound Service:
<serviceandroid:name=".MyBoundService"android:enabled="true"android:exported="true" />
  • 在其他组件(例如Activity)中绑定Bound Service:
private MyBoundService mBoundService;
private boolean mServiceBound = false;private ServiceConnection serviceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {MyBoundService.MyBinder binder = (MyBoundService.MyBinder) iBinder;mBoundService = binder.getService();mServiceBound = true;}@Overridepublic void onServiceDisconnected(ComponentName componentName) {mServiceBound = false;}
};@Override
protected void onStart() {super.onStart();Intent intent = new Intent(this, MyBoundService.class);bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}@Override
protected void onStop() {super.onStop();if (mServiceBound) {unbindService(serviceConnection);mServiceBound = false;}
}

通过上面的代码示例,我们演示了Android中两种启动Service的方法,Started Service通过startService()启动,而Bound Service通过bindService()绑定到其他组件上。Started Service适用于需要在后台执行耗时任务的场景,而Bound Service适用于需要与其他组件进行交互的场景。需要注意的是,Service的生命周期由启动或绑定的组件决定,在不需要使用Service时应及时停止或解绑。

http://www.lryc.cn/news/99457.html

相关文章:

  • 测试开源C#人脸识别模块ViewFaceCore(5:质量检测和眼睛状态检测)
  • Go语言网络库net/http
  • Acwing.91 最短Hamilton路径(动态规划)
  • [hfut] [important] v4l2 vedio使用总结/opevx/ffpeg/v4l2/opencv/cuda
  • 2023年深圳杯数学建模A题影响城市居民身体健康的因素分析
  • 指令调度(Instruction Scheduling)
  • 【运维】Linux 跨服务器复制文件文件夹
  • k8s apiserver如何支持http访问?
  • Safetensors,高效安全易用的深度学习新工具
  • Unity 工具之 NuGetForUnity 包管理器,方便在 Unity 中的进行包管理的简单使用
  • 运算放大器(二):恒流源
  • 企业选择租用CRM还是一次性买断CRM?分别有哪些优势?
  • VBA_MF系列技术资料1-133
  • Android 项目架构
  • 【Linux】进程通信 — 管道
  • ROS 2 — 托管(生命周期)节点简介
  • vue2企业级项目(六)
  • OSPF的选路原则
  • 4.操作元素属性
  • uniapp 微信小程序:v-model双向绑定问题(自定义 props 名无效)
  • 【Lua学习笔记】Lua进阶——Table(3) 元表
  • AI编程常用工具 Jupyter Notebook
  • RocketMQ重复消费的解决方案::分布式锁直击面试!
  • 如何降低TCP在局域网环境下的数据传输延迟
  • 【LeetCode】78.子集
  • 认可功能介绍 - 技术声誉靠认可
  • EtherNet/IP转CAN网关can协议标准
  • 解决代理IP负载均衡与性能优化的双重挑战
  • 深度探索 Elasticsearch 8.X:function_score 参数解读与实战案例分析
  • 测牛学堂:软件测试之andorid app性能测试面试知识点总结(二)