前面介绍的Service在官方文档介绍中说Service存在着如下两个问题:

1.A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.

2.A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

1、Service不会专门启动一条单独的进程,Service与它所在的应用在同一个进程中。

2、Service不是专门一条新的线程,因此不能再Service中直接处理耗时任务。

如果开发者在Service中处理耗时任务,建议在Service中另外启动一条新的线程来处理耗时的任务,可能有的朋友就会问:“既然在Service中处理耗时任务需要启动新线程,为什么我们不直接在Activity中开启一个新线程,而要使用Service呢?”

其实这种在Activity中直接启动一个线程来实现对有些业务逻辑是非常不可靠的,比如:用户使用BroadcastReceiver来启动一个新线程,BroadcastReceiver的生命周期非常短,这样就可能存在这样的问题,在子线程还没有结束的情况下,BroadcastReceiver已经结束了,或者用户在Activity中启动一个新线程后直接退出,此时它们所在的进程就变成了空进程(没有任何活动组件的进程),系统需要内存时可能会优先终止该进程。如果宿主进程被终止,那么该进程内的所有子线程也会被终止,这样就有可能导致一些严重错误。

IntentService是Service的子类,所以它比Service增加了额外的功能,它正好弥补了Service的上述两点不足:IntentService将会使用队列来管理请求Intent,每当客户端代码通过Intent请求启动IntentService时,IntentService会将该Intent加入队列中,然后开启一条新的worker线程来处理该Intent.对于异步的startService()请求,IntentService会按次序依次处理队列中的Intent,该线程保证同一时刻只处理一个Intent.由于IntentService使用新的worker线程处理Intent请求,因此IntentService不会阻塞主线程,所以IntentService就可以处理耗时任务。

IntentService有如下特征:

1、会创建单独的worker线程来处理所有的Intent请求。

2、会创建单独的worker线程来处理onHandleIntent()方法实现的代码。

3、所有请求处理完成后,IntentService会自动停止,因此开发者无须调用stopSelf()方法

4、为Service的onBind()方法提供了默认的实现,默认实现的onBind()方法返回null

5、为Service的onStartCommand()方法提供了默认实现,该实现会将请求的Intent添加到队列中。

从上面的特点中可以看出来,扩展的IntentService实现Service无须重写onBind()方法和onStartCommand()方法,只要重写onHandleIntent()方法即可。

下面通过一个具体例子来说明IntentService和Service的区别:

(1)继承自Service的MyService类

package com.example.testservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyService extends Service{ @Override
public IBinder onBind(Intent intent) { return null;
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
//该方法内可以执行耗时任务,比如下载文件等
long endTime = System.currentTimeMillis() + 20 * 1000;
System.out.println("onStart");
while(System.currentTimeMillis() < endTime){
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("--耗时任务执行完毕--");
return START_STICKY;
}
}

读者可能会注意到onStartCommand方法最后的返回值我设置成了START_STICKY,有关返回值的详细设置及含义将在下一篇文章中介绍。

执行结果

可以看到在Service中执行耗时任务程序的主UI会被阻塞,出现ANR异常。

(2)继承自IntentService的MyIntentService类

package com.example.testservice;

import android.app.IntentService;
import android.content.Intent; public class MyIntentService extends IntentService{ public MyIntentService(){
super("MyIntentService");
} @Override
protected void onHandleIntent(Intent arg0) {
//该方法内可以执行耗时任务,比如下载文件等
long endTime = System.currentTimeMillis() + 20 * 1000;
System.out.println("onStart");
while(System.currentTimeMillis() < endTime){
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("--耗时任务执行完毕--");
}
}

执行结果:

Android菜鸟的成长笔记(20)——IntentService的更多相关文章

  1. Android菜鸟的成长笔记(5)——Android系统源代码你下载了吗?

    原文:Android菜鸟的成长笔记(5)--Android系统源代码你下载了吗? 在上一篇中我们用Android系统源代码分析了我们前面写的代码,有的朋友可能就会问怎么才能下载到Google官方的源代 ...

  2. Android菜鸟的成长笔记(3)——给QQ登录界面说So Easy

    原文:Android菜鸟的成长笔记(3)--给QQ登录界面说So Easy 上一篇:Android菜鸟的成长笔记(2)--第一个Android应用 我们前面已经做了第一个Android应用程序,虽然有 ...

  3. Android菜鸟的成长笔记(2)——第一个Android应用

    原文:Android菜鸟的成长笔记(2)--第一个Android应用 上一篇:Android菜鸟的成长笔记(1)--Anddroid环境搭建从入门到精通 在上一篇Android菜鸟的成长笔记(1)中我 ...

  4. Android菜鸟的成长笔记(1)——Android开发环境搭建从入门到精通

    原文:Android菜鸟的成长笔记(1)--Android开发环境搭建从入门到精通 今天在博客中看到好多Android的初学者对Android的开发环境的搭建不熟悉而导致不能进行学习,所以我决定自己写 ...

  5. Android菜鸟的成长笔记(14)—— Android中的状态保存探究(上)

    原文:[置顶] Android菜鸟的成长笔记(14)—— Android中的状态保存探究(上) 我们在用手机的时候可能会发现,即使应用被放到后台再返回到前台数据依然保留(比如说我们正在玩游戏,突然电话 ...

  6. Android菜鸟的成长笔记(13)——异步任务(Async Task)

    原文:[置顶] Android菜鸟的成长笔记(13)——异步任务(Async Task) Android的UI线程主要负责处理用户的事件及图形显示,因此主线程UI不能阻塞,否则会弹出一个ANR(App ...

  7. Android菜鸟的成长笔记(12)——Handler、Loop、MessageQueue

    原文:[置顶] Android菜鸟的成长笔记(12)——Handler.Loop.MessageQueue 当一个程序第一次启动时,Android会启动一条主线程(Main Thread),主线程主要 ...

  8. Android菜鸟的成长笔记(11)——Android中的事件处理

    原文:[置顶] Android菜鸟的成长笔记(11)——Android中的事件处理 Android提供了两种方式来处理事件,一个是基于回调的事件处理,另一个是基于监听的事件处理,举个例子: 基于回调的 ...

  9. Android菜鸟的成长笔记(10)——使用Bundle在Activity之间传值

    原文:[置顶] Android菜鸟的成长笔记(10)——使用Bundle在Activity之间传值 前面我们了解了如何启动一个Activity,一个Activity在启动另外一个Activity的时候 ...

  10. Android菜鸟的成长笔记(9)——Intent与Intent Filter(下)

    原文:[置顶] Android菜鸟的成长笔记(9)——Intent与Intent Filter(下) 接着上一篇的内容,下面我们再来看看Intent的Data与Type属性. 一.Data属性与Typ ...

随机推荐

  1. Linux定时器的使用(三种方法)

    使用定时器的目的无非是为了周期性的执行某一任务,或者是到了一个指定时间去执行某一个任务.要达到这一目的,一般有两个常见的比较有效的方法.一个是用linux内部的三个定时器,另一个是用sleep, us ...

  2. android 蓝牙各种UUID

    ServiceDiscoveryServerServiceClassID_UUID = '{00001000-0000-1000-8000-00805F9B34FB}' BrowseGroupDesc ...

  3. C++ BYTE数组转字符串

    第一种情况: BYTE[0]=Ox12 BYTE[1]=0x34 BYTE[2]=0x56 最后要转换成字符串123456 另外一种情况: BYTE[0]=Ox12 BYTE[1]=0x34 BYTE ...

  4. Maven基础教程 分类: C_OHTERS 2015-04-10 22:53 232人阅读 评论(0) 收藏

    更多内容请参考官方文档:http://maven.apache.org/guides/index.html 官方文档很详细,基本上可以查找到一切相关的内容. 另外,快速入门可参考视频:孔浩的maven ...

  5. poj1564 Sum It Up (zoj 1711 hdu 1258) DFS

    POJhttp://poj.org/problem?id=1564 ZOJhttp://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=711 ...

  6. 关于spring获取webApplication.getBean多种途径和简单解释

    ApplicationContext ac1 = new FileSystemXmlApplicationContext("com/spark/system/applicationConte ...

  7. SDUT OJ 2862 勾股定理

    #include<iostream> using namespace std; int a[1010]; void qsort(int a[],int l,int r) { int x=a ...

  8. Linux 系统挂载数据盘 分类: B3_LINUX 2015-01-30 18:13 228人阅读 评论(0) 收藏

    适用系统:Linux(Redhat , CentOS,Debian,Ubuntu) *  Linux的云服务器数据盘未做分区和格式化,可以根据以下步骤进行分区以及格式化操作. 下面的操作将会把数据盘划 ...

  9. Chinese remainder theorem

    https://en.wikipedia.org/wiki/Chinese_remainder_theorem http://planetmath.org/ChineseRemainderTheore ...

  10. Java虚拟机解析篇之---内存模型

    今天闲来无事来,看一下Java中的内存模型和垃圾回收机制的原理.关于这个方面的知识,网上已经有非常多现成的资料能够供我们參考,可是知识还是比較杂的,在这部分知识点中有一本书不得不推荐:<深入理解 ...