Android Service进阶之路

一、Service基础

1. Service是什么?

  Service是一种在后台长时间运行,但是没有界面与用户交互的组件。在App退出时,Service依然在后台运行,这就是Service保活。  

  Service与BoradCast都是运行在主线程中。所以,Service不能执行耗时操作。

2. Service与Thread的区别?

  原因1:

  Thread是OS运行的最小执行单元,运行是相对独立的。

  Service是Android的一种后台服务,Service是运行在Android主线程里。当App退出,Service也可以运行在后台,不会因为App终止运行而终止。由于Service是运行在主线程中,所以Service不能执行耗时逻辑,所以通过会在Service中创建Thread(线程)执行耗时逻辑。

  原因2:

  在实际开发过程中,在Android中,线程一般指的是工作线程。

  原因3:

   Service使用场景上,耗时网络、文件读取上、后台听音乐等,比较耗时操作或者在后台执行的操作,可以使用Service。

  

问题1:Service运行在线程中,不能执行耗时逻辑,如果执行耗时逻辑需要在Service创建子线程完成,这样,为什么不直接在Activity中创建子线程完成相应耗时逻辑?

  因为在Activity中创建Thread,Activity很难对子线程进行控制,当Activity销毁后,就无法获取到Thread的实例对象。在管理和使用上不方便。而在Service上创建子线程,Activity销毁后,依然可以通过Service对子线程进行控制。  

二、开启Service方式

  1. StartService

    在Activity中,通过startService(...)方法启动服务,即使应用程序退出了,Service依然在后台中无限期执行。除非使stopService(...)或者stopSelf()方法终止Service。    

  2. BindService

  在Activity中通过bindService()方法绑定服务

 1         ServiceConnection conn = new ServiceConnection() {
 2             @Override
 3             public void onServiceConnected(ComponentName name, IBinder service) {
 4                 BindService.MyBinder binder = (BindService.MyBinder) service;
 5                 BindService service1 = binder.getService();
 6                 Log.d("bindservice log: ", String.valueOf(service1.getRadom()));
 7             }
 8 
 9             @Override
10             public void onServiceDisconnected(ComponentName name) {
11 
12             }
13         };
14 
15         Intent bIntent = new Intent();
16         bIntent.setClass(this, BindService.class);
17         bindService(bIntent, conn, BIND_AUTO_CREATE);    

  在BindService中继承Binder类

 1     private MyBinder mMyBinder = new MyBinder();
 2     
 3     public class MyBinder extends Binder {
 4         public BindService getService() {
 5             return BindService.this;
 6         }
 7     }
 8 
 9     @Override
10     public IBinder onBind(Intent intent) {
11         return mMyBinder;
12     }

 

posted @ 2021-09-20 16:44  naray  阅读(103)  评论(0编辑  收藏  举报