Service是Android中四大组件之一,在Android开发中起到非常重要的作用,它运行在后台,不与用户进行交互。

1、Service的继承关系:

java.lang.Object → android.content.Context → android.content.ContextWrapper → android.app.Service

2、Sevice定义:

Service(服务)是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。

3、Service有两种状态," 启动的 " 和 " 绑定 ":

[1]通过startService()启动的服务处于" 启动的 "状态,一旦启动,service就在后台运行,即使启动它的应用组件已经被销毁了。通常started状态的service执行的任务并且不返回任何结果给启动者。比如当下载或上传一个文件,当这项操作完成时,service应该停止它本身。

[2]" 绑定 "状态:通过调用bindService()来启动,一个绑定的service提供一个允许组件与service交互的接口,可以发送请求、获取返回结果,还可以通过夸进程通信来交互(IPC)。绑定的service只有当应用组件绑定后才能运行,多个组件可以绑定一个service,当调用unbind()方法时,这个service就会被销毁了。

注意:默认情况下,service与activity一样都存在与当前进程的主线程中,所以,一些阻塞UI的操作,比如耗时操作不能放在service里进行,比如另外开启一个线程来处理诸如网络请求的耗时操作。如果在service里进行一些耗CPU和耗时操作,可能会引发ANR警告,这时应用会弹出是强制关闭还是等待的对话框。所以,对service的理解就是和activity平级的,只不过是看不见的,在后台运行的一个组件,这也是为什么和activity同被说为Android的基本组件。启动后的Service具有较高的优先级,一般情况下,系统会保证Service的正常运行,只有当前台的Activity正常运行的资源被Service占用的情况下,系统才会停止Service;当系统重新获得资源后,会根据程序的设置来决定是否重新启动原来的Service。

4、Service的生命周期:

        

 注意:bind service的不同之处在于当绑定的组件销毁后,对应的service也就被kill了。

service生命周期也涉及一些回调方法,这些方法都不用调用父类方法,具体如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class ExampleService extends Service {
    int mStartMode;       // indicates how to behave if the service is killed
    IBinder mBinder;      // interface for clients that bind
    boolean mAllowRebind; // indicates whether onRebind should be used
 
    @Override
    public void onCreate() {
        // The service is being created
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // The service is starting, due to a call to startService()
        return mStartMode;
    }
    @Override
    public IBinder onBind(Intent intent) {
        // A client is binding to the service with bindService()
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        // All clients have unbound with unbindService()
        return mAllowRebind;
    }
    @Override
    public void onRebind(Intent intent) {
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }
    @Override
    public void onDestroy() {
        // The service is no longer used and is being destroyed
    }
}

5、Service的一个子类:IntentService

IntentService使用队列的方式将请求的Intent加入队列,然后开启一个worker thread(线程)来处理队列中的Intent,对于异步的startService请求,IntentService会处理完成一个之后再处理第二个,每一个请求都会在一个单独的worker thread中处理,不会阻塞应用程序的主线程,因此,这里提供一个思路,如果有耗时的操作与其在Service里面开启新线程还不如使用IntentService来处理耗时操作。而在一般的继承Service里面如果要进行耗时操作就必须另开线程,但是使用IntentService就可以直接在里面进行耗时操作,因为默认实现了一个worker thread。

实现实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class defaultIntentService extends IntentService {
 
  //必须有构造函数, 并且必须带有worker thread的name作为参数调用super IntentService(String)
  public defaultIntentService() {
      super("defaultIntentService");
  }
 
  //通过从默认worker thread调用此带有intent的方法启动service
  //当方法返回IntentService会适时停止service<br>  @Override
  protected void onHandleIntent(Intent intent) {
      // 通常我们会做一些比如下载文件等的工作.
      // 比如实例中,睡眠五秒.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              catch (Exception e) {
              }
          }
      }
  }
}

6、停止Service

[1]如果service是非绑定的,最终当任务完成时,为了节省系统资源,一定要停止service,可以通过stopSelf()来停止,也可以在其他组件中通过stopService()来停止;

[2]绑定的service可以通过onUnBind()来停止service。

[Android四大组件之二]——Service的更多相关文章

  1. Android 四大组件之二(Service)

    service可以在和多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等,总之服务 ...

  2. Android四大组件初识之Service

    Service作为Android四大组件之一,可以与Activity建立双向连接(绑定模式),提供数据和功能.也能够接收Intent单方面请求(调用模式),进行数据处理和调度功能. Service与A ...

  3. 入职小白随笔之Android四大组件——服务(Service)

    Service Android多线程编程 当我们在程序中执行一些耗时操作时,比如发起一条网络请求,考虑到网速等原因,服务器未必会立刻响应我们的请求,此时我们就需要将这些操作放在子线程中去运行,以防止主 ...

  4. Android四大组件之服务-Service 原理和应用开发详解

    一.Android 服务简介 Service是android 系统中的四大组件之一(Activity.Service.BroadcastReceiver.ContentProvider),它跟Acti ...

  5. Android 四大组件(Activity、Service、BroadCastReceiver、ContentProvider)

    转载于:http://blog.csdn.net/byxdaz/article/details/9708491 http://blog.csdn.net/q876266464/article/deta ...

  6. 6、四大组件之二-Service初步

    一.什么是Service 有些用时比较长得操作我们希望他在后台运行 ,不耽误我们当前的操作 . 这就引入了Service概念 . 常见的比如:访问网络 , 文件IO操作 , 大数据的数据库任务,播放音 ...

  7. Android四大组件之一:Service(服务)

    Service跟Activity也是出于统一级别的组件,且与Activity的最大区别之一主要是没有人机界面,主要是运行在程序的后台(我是这么理解的),帮助文档上说的是运行于进程的主线程中,但是服务并 ...

  8. 11、四大组件之二-Service高级(二)Native Service

    一.Service的分类 1.1>Android Service 使用Java编写在JVM中运行的服务 1.2>Native Service 使用C/C++完成的服务,一般在系统开始时完成 ...

  9. 7、四大组件之二-Service高级

    一.Native Service 1>什么是Native Service 使用JNI编写,在系统启动完成之前启动的系统级服务. 2>哪些服务是Native Service ACCESSIB ...

随机推荐

  1. vue2.0 keep-alive最佳实践

    1.基本用法 vue2.0提供了一个keep-alive组件用来缓存组件,避免多次加载相应的组件,减少性能消耗 <keep-alive> <component> <!-- ...

  2. hibernate中复合主键的使用

    转: https://blog.csdn.net/shutingwang/article/details/6627730 https://blog.csdn.net/lmy86263/article/ ...

  3. set_index() pandas

    set_index DataFrame可以通过set_index方法,可以设置单索引和复合索引. DataFrame.set_index(keys, drop=True, append=False, ...

  4. 使用rownum对oracle分页【原】

    以Student表为例进行分页 建表及插入 -- 有表结构如下 create table STUDENT ( sno INTEGER, sname ), sage INTEGER ); -- 插入数据 ...

  5. Django 2.0.1 官方文档翻译:编写你的第一个djang补丁(page 15)

    编写你的第一个djang补丁(page 15) 介绍 有兴趣为社区做一些贡献?可能你发现了django中的一个你想修复的bug,或者你你想添加一个小小的功能. 回馈django就是解决你遇到的问题的最 ...

  6. postgresql时间处理

    时间取到截取 例:select date_trunc('second', "reportTime") from travel_message limit 10; 结果: 他人博客: ...

  7. Keil软仿真STM32

    当使用Keil软仿真STM32时,SystemClock设置为72MHz,使用循环延迟1s钟,实际时间明显大于1S钟,但是Keil调试窗口显示的确实是1s钟//毫秒级的延时void delay_ms( ...

  8. 支付宝app支付流程

  9. ubuntu18.04使用sudo时反应时间长

    一.查看/etc/sudoer这个文件,是否有当前用户,若无,请联系 管理员或者是通过root用户添加 二.用hostname命令查看自己的主机名 三.添加自己的主机名到/etc/hosts文件中

  10. C# 简单的反射机制实例

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.R ...