博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android-Service
阅读量:4291 次
发布时间:2019-05-27

本文共 3865 字,大约阅读时间需要 12 分钟。

Service是Android中四大组件之一,在Android开发中起到非常重要的作用,先来看一下官方对Service的定义:(安卓文档中的:)
翻译过来就是:Service(服务)是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。
Service有两种状态,“启动的”和“绑定”:
startService()
通过startService()启动的服务处于“启动的”状态,一旦启动,service就在后台运行,即使启动它的应用组件已经被销毁了。通常started状态的service执行单任务并且不返回任何结果给启动者。比如当下载或上传一个文件,当这项操作完成时,service应该停止它本身。stopSelf()也可用来停止。
bindService()
还有一种“绑定”状态的service,通过调用bindService()来启动,一个绑定的service提供一个允许组件与service交互的接口,可以发送请求、获取返回结果,还可以通过夸进程通信来交互(IPC)。绑定的service只有当应用组件绑定后才能运行,多个组件可以绑定一个service,当调用unbind()方法时,这个service就会被销毁了。
另外,在官方的说明文档中还有一个警告:
意思是
service与activity一样都存在与当前进程的主线程中,所以,一些阻塞UI的操作,比如耗时操作不能放在service里进行,比如另外开启一个线程来处理诸如网络请求的耗时操作。如果在service里进行一些耗CPU和耗时操作,可能会引发ANR警告,这时应用会弹出是强制关闭还是等待的对话框。所以,对service的理解就是和activity平级的,只不过是看不见的,在后台运行的一个组件,这也是为什么和activity同被说为Android的基本组件。
Service生命周期中的一些方法:

通过这个图可以看到,两种启动service的方式以及他们的生命周期,bind service的不同之处在于当绑定的组件销毁后,对应的service也就被kill了。service的声明周期相比与activity的简单了许多,只要好好理解两种启动service方式的异同就行。

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    }}
另外,这里要说明Service的一个子类,
IntentService,首先看下官方文档的说明:
IntentService使用队列的方式将请求的Intent加入队列,然后开启一个worker thread(线程)来处理队列中的Intent,对于异步的startService请求,IntentService会处理完成一个之后再处理第二个,每一个请求都会在一个单独的worker thread中处理,不会阻塞应用程序的主线程,这里就给我们提供了一个思路,如果有耗时的操作与其在Service里面开启新线程还不如使用IntentService来处理耗时操作。而在一般的继承Service里面如果要进行耗时操作就必须另开线程,但是使用IntentService就可以直接在里面进行耗时操作,因为默认实现了一个worker thread。对于异步的startService请求,IntentService会处理完成一个之后再处理第二个。
看下IntentService的具体实现:

public class HelloIntentService extends IntentService {  /**    * A constructor is required, and must call the super IntentService(String)   * constructor with a name for the worker thread.   */  public HelloIntentService() {      super("HelloIntentService");  }  /**   * The IntentService calls this method from the default worker thread with   * the intent that started the service. When this method returns, IntentService   * stops the service, as appropriate.   */  @Override  protected void onHandleIntent(Intent intent) {      // Normally we would do some work here, like download a file.      // For our sample, we just sleep for 5 seconds.      long endTime = System.currentTimeMillis() + 5*1000;      while (System.currentTimeMillis() < endTime) {          synchronized (this) {              try {                  wait(endTime - System.currentTimeMillis());              } catch (Exception e) {              }          }      }  }}
控制service运行的主要方式有两种,主要是根据onStartCommand方法返回的数值。
1、  START_STICKY
2、  START_NOT_STICKY
3、  START_REDELIVER_INTENT

权限

         要运行service,首先必须在AndroidManifest.xml里申明<service>标签。

         Service能够保护个人的IPC调用,所以在执行实现该调用时前先使用
checkCallingPermission(String)方法检查是否有这个权限。

转载地址:http://syegi.baihongyu.com/

你可能感兴趣的文章
javascript面试的5个冷门知识点
查看>>
Lucene初探
查看>>
Git简介、安装及创建版本库
查看>>
如何在JavaScript中编写一个简单的Bug跟踪器
查看>>
jQuery 效果 - 滑动
查看>>
对Java多态的深入理解
查看>>
javascript重点-表达式和运算符_优就业
查看>>
springmvc整合poi导出报表
查看>>
Oracle Data Guard延迟的原因
查看>>
java8 遍历数组的几种方式
查看>>
java基础知识(七)--Object类
查看>>
Object.prototype.toString_优就业
查看>>
JS之浏览器对象BOM
查看>>
JAVA面试、进阶必备——堆内存与栈内存
查看>>
springboot(十一):Spring boot中mongodb的使用
查看>>
Java基础之IO流判断文件夹或文件是否存在及其如何创建?
查看>>
java系列(八)枯燥的基础总结
查看>>
北漂面试经历(一(两)年工作经验)——Java基础部分
查看>>
一道有关内存泄漏的阿里巴巴JAVA工程师笔试题
查看>>
多线程之synchronized锁字符串对象的一个易错点
查看>>