Android四大组件:Service

前言

  • Service作为Android四大组件之一,应用非常广泛
  • 本文将介绍对Service进行全面介绍(基础认识、生命周期、使用和应用场景)

目录


目录

1. 基础知识

  • 定义:服务,属于Android中的计算型组件
  • 作用:提供需要在后台长期运行的服务(如复杂计算、下载等等)
  • 特点:长生命周期的、没有用户界面、在后台运行

2. 生命周期方法详解

具体请看我写的文章:Android:Service生命周期最全面解析


3. Service分类

3.1 Service的类型


分类

3.2 详细介绍


Service类型的详细介绍

4. Service的使用解析

由上述可知,服务Service总共分为:


分类

接下来,我将介绍每种Service的具体使用,具体请看我写的文章:Android:(本地、可通信的、前台、远程)Service使用全面介绍

5. 使用场景

  • 通过上述描述,你应该对Service类型及其使用非常了解;
  • 那么,我们该什么时候用哪种类型的Service呢?
  • 各种Service的使用场景请看下图:

    使用场景

6. 其他思考

6.1 Service和Thread的区别

  • 结论:Service和Thread之间没有任何关系
  • 之所以有不少人会把它们联系起来,主要因为Service的后台概念

    后台的定义:后台任务运行完全不依赖UI,即使Activity被销毁,或者程序被关闭,只要进程还在,后台任务就可以继续运行

  • 其实二者存在较大的区别,如下图:


    Paste_Image.png

一般来说,会将Service和Thread联合着用,即在Service中再创建一个子线程(工作线程)去处理耗时操作逻辑,如下代码:

@Override  
public int onStartCommand(Intent intent, int flags, int startId) {  
//新建工作线程
    new Thread(new Runnable() {  
        @Override  
        public void run() {  
            // 开始执行后台任务  
        }  
    }).start();  
    return super.onStartCommand(intent, flags, startId);  
}  

class MyBinder extends Binder {  
    public void service_connect_Activity() {  
  //新建工作线程
        new Thread(new Runnable() {  
            @Override  
            public void run() {  
                // 执行具体的下载任务  
            }  
        }).start();  
    }  

}
原文地址:https://www.cnblogs.com/xinmengwuheng/p/7070187.html