当前位置:   article > 正文

Android四大组件之一服务(Service)详解_android 服务 service

android 服务 service

什么是服务

        当谈论 Android 应用组件时,服务(Service)是四大组件之一,用于在后台执行长时间运行的操作或为多个组件提供共享的处理。服务没有用户界面,通常在后台运行,并且可以与其他应用组件进行通信。以下是关于 Android 服务的一些重要概念和讲解:

1. 服务的类型:

  • 前台服务(Foreground Service):

    • 在通知栏显示一个通知,使用户知晓服务正在运行。
    • 常用于执行用户明确请求的操作,如音乐播放器或下载服务。
  • 后台服务(Background Service):

    • 在后台默默执行任务,用户通常不直接感知。
    • 例如,检查新邮件或上传数据。

2. 服务的生命周期:

服务有三种状态:

  • 创建(Created):

    • 通过调用 startService()bindService() 启动服务时进入此状态。
    • onCreate()onStartCommand() 方法会被调用。
  • 运行(Started/Running):

    • 服务正在执行任务。
    • onStartCommand() 方法中定义的逻辑在此时执行。
  • 销毁(Destroyed):

    • 通过调用 stopSelf()stopService() 终止服务。
    • onDestroy() 方法被调用。

3. 服务的通信方式:

服务可以与其他组件进行通信:

  • 启动服务(Start Service):

    • 使用 startService() 方法启动服务。
    • 通过 Intent 传递数据。
  • 绑定服务(Bind Service):

    • 使用 bindService() 方法启动服务。
    • 返回一个用于与服务通信的 IBinder 对象。

4. 在清单文件中声明服务:

在 AndroidManifest.xml 文件中声明服务:

  1. <service
  2. android:name=".MyService"
  3. android:enabled="true"
  4. android:exported="false">
  5. <!-- 可以添加其他属性 -->
  6. </service>

示例详解

1、启动服务(startService

  1. 生命周期独立: 启动服务的生命周期与启动它的组件(通常是Activity)独立。即使启动服务的组件被销毁,服务仍然可以在后台继续执行。

  2. 返回结果: startService() 方法通常用于执行一次性任务,并且可以通过 startService() 的返回值或者服务中的 onStartCommand() 方法中的返回值传递结果。

  3. 多个组件: 多个组件可以同时启动同一个服务,而且服务只会有一个实例(即使被多个组件启动)。

  4. 通信通过Intent: 通过Intent传递数据给服务。

  5. 不可直接调用服务中的方法: 服务的方法不会直接暴露给其他组件,而是通过Intent传递数据。

  1. /**
  2. * @ClassName ServiceBackground
  3. * @Description 后台服务 通常用于在后台执行长时间运行的任务,例如下载、数据同步等。
  4. * @Author ZMROBO
  5. * @Date 2023/12/26 16:35
  6. */
  7. public class ServiceStudy extends Service {
  8. private static String TAG="ServiceStudy";
  9. /**
  10. * @description 不需要绑定 可以返回null
  11. */
  12. @Nullable
  13. @Override
  14. public IBinder onBind(Intent intent) {
  15. MlogUtil.d(TAG,"onBind");
  16. return null;
  17. }
  18. /**
  19. * @description 生命周期 1
  20. */
  21. @Override
  22. public void onCreate() {
  23. super.onCreate();
  24. MlogUtil.d(TAG,"onCreate");
  25. }
  26. /**
  27. * @description 生命周期 2 在这里执行逻辑
  28. */
  29. @Override
  30. public int onStartCommand(Intent intent, int flags, int startId) {
  31. MlogUtil.d(TAG,"onStartCommand");
  32. return super.onStartCommand(intent, flags, startId);
  33. }
  34. /**
  35. * @description 生命周期 3
  36. */
  37. @Override
  38. public void onDestroy() {
  39. super.onDestroy();
  40. MlogUtil.d(TAG,"onDestroy");
  41. }
  42. }
  1. //开启服务
  2. intent = new Intent(this, ServiceBackgroundForStart.class);
  3. startService(intent);

3、绑定服务( bindService

  1. 生命周期绑定: 绑定服务的生命周期与绑定它的组件(通常是Activity)相关联。当绑定的组件被销毁时,服务也会被解绑。

  2. 返回结果: bindService() 方法允许组件绑定到服务,并返回一个可以用于与服务进行通信的 IBinder 对象。这使得组件能够调用服务中的方法。

  3. 单一组件: 绑定服务通常是为了在一个Activity中执行与服务相关的操作,因为一个服务只能被一个组件绑定。

  4. 直接调用服务中的方法: 绑定服务提供了直接调用服务中方法的方式,因为它返回一个可以用于与服务进行通信的 IBinder 对象。

  5. 通信通过IBinder: 绑定服务通常用于实现应用内的组件通信,而不是与外部服务通信。

  1. /**
  2. * @ClassName ServiceBackgroundForBind
  3. * @Description 使用绑定的形式调用
  4. * @Author ZMROBO
  5. * @Date 2023/12/27 10:52
  6. */
  7. public class ServiceBackgroundForBind extends Service {
  8. private static final String TAG = ServiceBackgroundForBind.class.getSimpleName();
  9. /**
  10. * @description 创建MyBinder类
  11. */
  12. private MyBinder myBinder = new MyBinder();
  13. /**
  14. * @description 返回IBinder对象
  15. */
  16. @Nullable
  17. @Override
  18. public IBinder onBind(Intent intent) {
  19. MlogUtil.d(TAG,"生命周期:onBind");
  20. return myBinder;
  21. }
  22. @Override
  23. public void onCreate() {
  24. super.onCreate();
  25. MlogUtil.d(TAG,"生命周期:onCreate");
  26. }
  27. @Override
  28. public int onStartCommand(Intent intent, int flags, int startId) {
  29. MlogUtil.d(TAG,"生命周期:onStartCommand");
  30. return super.onStartCommand(intent, flags, startId);
  31. }
  32. @Override
  33. public void onDestroy() {
  34. super.onDestroy();
  35. MlogUtil.d(TAG,"生命周期:onDestroy");
  36. }
  37. /**
  38. * @description 暴露给外部调用
  39. */
  40. public void doSomething() {
  41. MlogUtil.d(TAG,"执行服务的逻辑");
  42. }
  43. /**
  44. * @description IBInder类
  45. */
  46. public class MyBinder extends Binder {
  47. public ServiceBackgroundForBind getService() {
  48. return ServiceBackgroundForBind.this;
  49. }
  50. }
  51. }

使用

  1. public class MainActivity extends BaseActivity {
  2. private static final String TAG = MainActivity.class.getSimpleName();
  3. private Intent intent;
  4. /**
  5. * @description 是否绑定
  6. */
  7. private boolean isBound = false;
  8. private ServiceBackgroundForBind service;
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_main);
  13. /*start服务
  14. intent = new Intent(this, ServiceBackgroundForStart.class);
  15. startService(intent);*/
  16. //绑定服务
  17. intent = new Intent(this, ServiceBackgroundForBind.class);
  18. // Context.BIND_AUTO_CREATE 表示如果服务不存在,则应创建它
  19. bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
  20. }
  21. /**
  22. * @description 这里执行服务里的方法 可以传参数 或者获取服务的数据 具体需求而定
  23. */
  24. public void doSomething() {
  25. MlogUtil.d(TAG,"doSomething: "+isBound+" ");
  26. if (isBound&& service != null) {
  27. service.doSomething();
  28. }
  29. }
  30. /**
  31. * @description 连接服务 监听服务是否绑定 用于处理连接和断开连接事件的 ServiceConnection
  32. */
  33. private ServiceConnection mServiceConnection = new ServiceConnection() {
  34. // 当与服务的连接时调用
  35. @Override
  36. public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
  37. isBound = true;
  38. ServiceBackgroundForBind.MyBinder binder = (ServiceBackgroundForBind.MyBinder) iBinder;
  39. //通过binder获取服务实例
  40. service = binder.getService();
  41. MlogUtil.d(TAG,"绑定状态:onServiceConnected "+isBound+" ");
  42. }
  43. // 当与服务的连接意外断开时调用
  44. @Override
  45. public void onServiceDisconnected(ComponentName componentName) {
  46. isBound = false;
  47. MlogUtil.d(TAG,"绑定状态:onServiceDisconnected "+isBound+" ");
  48. }
  49. };
  50. @Override
  51. protected void onDestroy() {
  52. super.onDestroy();
  53. /*if (intent != null) {
  54. stopService(intent);
  55. }*/
  56. //记得解绑
  57. if (isBound) {
  58. unbindService(mServiceConnection);
  59. }
  60. }
  61. public void doSomething(View view) {
  62. doSomething();
  63. }
  64. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/784120
推荐阅读
相关标签
  

闽ICP备14008679号