IntentService提供了一种在后台线程中运行任务的方式,适合处理运行时间较长的后台任务。

长处:

(1)IntentService执行在单独的线程中。不会堵塞UI线程

(2)IntentService不受生命周期的影响

缺点:

(1)不能与UI直接进行交互,能够用Broadcast

(2)顺序运行请求,第二个请求仅仅有在第一个请求运行完以后才干运行

(3)请求不能被中断

使用IntentService的步骤:

(1)在Activity中通过startService启动service,并传递參数。

(2)Service中接收參数,做耗时的处理。处理完成,发送Broadcat,并把处理结果传递出来

(3)Activity中注冊BroadcastReceiver,监听广播,更新UI。

看一个样例:

public class MainActivity extends Activity {

	@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) this.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {//通过startService启动service。并传递參数。
Intent mServiceIntent = new Intent(MainActivity.this,RSSPullService.class);
mServiceIntent.setData(Uri.parse("http://www.baidu.com/"));
MainActivity.this.startService(mServiceIntent);
}
});
//注冊BroadcastReceiver。监听广播
IntentFilter statusIntentFilter = new IntentFilter(Constants.BROADCAST_ACTION);
// Sets the filter's category to DEFAULT
statusIntentFilter.addCategory(Intent.CATEGORY_DEFAULT);
DownloadStateReceiver mDownloadStateReceiver = new DownloadStateReceiver();
// Registers the DownloadStateReceiver and its intent filters
LocalBroadcastManager.getInstance(this).registerReceiver(mDownloadStateReceiver, statusIntentFilter); } private class DownloadStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String data = intent.getStringExtra(Constants.EXTENDED_DATA);
Log.e("test", data);
Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
}
} }
public class RSSPullService extends IntentService {

	public RSSPullService() {
super("RSSPullService");
} @Override
protected void onHandleIntent(Intent workIntent) {//接收參数。做耗时的处理。处理完成。发送Broadcat
String localUrlString = workIntent.getDataString();
String data = download(localUrlString);
Intent localIntent = new Intent(Constants.BROADCAST_ACTION);
// Puts the status into the Intent
localIntent.putExtra(Constants.EXTENDED_DATA, data);
// Broadcasts the Intent to receivers in this app.
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
} private String download(String localUrlString){
try{
URL url = new URL(localUrlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while((len = in.read(buff)) != -1){
out.write(buff,0,len);
}
in.close();
return new String(out.toByteArray());
}catch(Exception e){
e.printStackTrace();
return "";
}
}
}
public class Constants {

	// Defines a custom Intent action
public static final String BROADCAST_ACTION = "com.example.android.threadsample.BROADCAST"; // Defines the key for the status "extra" in an Intent
public static final String EXTENDED_DATA_STATUS = "com.example.android.threadsample.STATUS"; public static final String EXTENDED_DATA = "com.example.android.threadsample.DATA"; }

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.intentservicedemo"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" /> <!-- Requires this permission to download RSS data from Picasa -->
<uses-permission android:name="android.permission.INTERNET" /> <!--
Defines the application.
-->
<application
android:icon="@drawable/icon"
android:label="@string/app_name"> <activity
android:name="com.example.android.intentservicedemo.MainActivity"
android:label="@string/activity_title" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <!--
No intent filters are specified, so android:exported defaults to "false". The
service is only available to this app.
-->
<service
android:name="com.example.android.intentservicedemo.RSSPullService"
android:exported="false"/> </application> </manifest>

參考:http://developer.android.com/training/run-background-service/index.html

Android中使用IntentService运行后台任务的更多相关文章

  1. Android中的IntentService

    首先说下,其他概念:Android中的本地服务与远程服务是什么? 本地服务:LocalService 应用程序内部------startService远程服务:RemoteService androi ...

  2. iOS 和 Android 中的后台运行问题

    后台机制的不同,算是iOS 和 Android的一大区别了,最近发布的iOS7又对后台处理做了一定的更改,找时间总结一下编码上的区别,先做个记录. 先看看iOS的把,首先需要仔细阅读一下Apple的官 ...

  3. Android中获取正在运行的应用程序-----ActivityManager.RunningAppProcessInfo类详解

    今天继续讲解关于ActivityManager的使用,通过前面一节的学习,我们学会了如何利用ActivityManager获取系统里 正在运行的进程.本文要讲解的知识点是利用这些进程信息获取系统里正在 ...

  4. Android中获取正在运行的服务-------ActivityManager.RunningServiceInfo的使用

    关于PackageManager和ActivityManager的使用 ,自己也写了一些DEMO 了,基本上写的线路参考了Settings模块下的 应用程序,大家如果真正的有所兴趣,建议大家看看源码, ...

  5. Android Training - 使用IntentService运行任务(Lesson 2 - 发送任务给IntentService)

    写在http://hukai.me/blog/android-training-18-running-background-service-lesson-2/

  6. Android Training - 使用IntentService运行任务(Lesson 1 - 创建IntentService)

    写在http://hukai.me/blog/android-training-18-running-background-service-lesson-1/ 版权声明:本文博客原创文章,博客,未经同 ...

  7. 在Android中使用并发来提高速度和性能

    Android框架提供了很实用的异步处理类.然而它们中的大多数在一个单一的后台线程中排队.当你需要多个线程时你是怎么做的? 众所周知,UI更新发生在UI线程(也称为主线程).在主线程中的任何操作都会阻 ...

  8. [Android] Service和IntentService中显示Toast的区别

    1. 表象     Service中可以正常显示Toast,IntentService中不能正常显示Toast,在2.3系统上,不显示toast,在4.3系统上,toast显示,但是不会消失. 2. ...

  9. 在Android中用Kotlin的Anko运行后台任务(KAD 09)

    作者:Antonio Leiva 时间:Jan 19, 2017 原文链接:https://antonioleiva.com/anko-background-kotlin-android/ Anko是 ...

随机推荐

  1. 彻底解决 Intellij IDEA 卡顿 优化笔记,重要的快捷键

    由于工作中经常出现分支各种切换,使用Eclipse便不再像以前那么舒服了,不停的修改工作空间,每次修改完工作空间又是一堆一堆的个性化设置,来回的切换,真的很累.我们做软件的,怎么能不去尝试新鲜的呢,毕 ...

  2. 【jeecg-mybatis版本】 mybatis+spring mvc 完美整合方案 查询,保存,更新,删除自动生成

    Jeecg-Mybatis版本代码生成器演示视频 http://pan.baidu.com/share/link?shareid=243717&uk=2668473880   简要说明  JE ...

  3. 树莓派系统(Debain)中设置SSH服务开机自启动

    一.方式: 禁用命令:sudo update-rc.d ssh disable 启用命令:sudo update-rc.d ssh enable 二.chkconfig的方式: 1.安装:apt-ge ...

  4. websocket与canvas[转]

    server端还是用tomcat7的方式客户端 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  ...

  5. WIP 002- Rating info page design

    Please design the screen When Permitted Subdivision selected Yes hide Flood Zone, otherwise show it.

  6. Git如何获得两个版本间所有变更的文件列表

    https://segmentfault.com/q/1010000000133613 git diff --name-status HEAD~2 HEAD~3

  7. Android——自定义多击事件

    一:使用场景 Android本身内置了点击.双击事件,但是某些时候,我们可能需要多击事件. 例如:某个秘密入口,为了避免用户误操作点击.双击到了触发开关而进入到不该被用户看到的页面,我们可以为入口控件 ...

  8. ES6学习笔记五:Promise异步任务

    一:Promise对象 Promise对象代表一个异步操作,有三种状态:Pending(进行中).Resolved(已完成,又称 Fulfilled)和Rejected(已失败). 二:创建与使用 v ...

  9. Python定向爬虫实战

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/7019963.html 一:requests模块介绍 requests是第三方http库,可以十分方便地实现py ...

  10. Eclipse项目修改没有同步到编译的问题

    有两个原因: 1:项目有错,不能正常编译:查看是否有Jar包冲突.JDK版本问题等: 2:编译输出目录配置错误: Maven项目会修改项目编译时的输出路径到target文件夹,但是我们用Myelips ...