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. GB2312码表

    GB2312码表 code +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F A1A0 . . · ˉ ˇ ¨ " 々 — - | … ‘ ’ ...

  2. C#.NET常见问题(FAQ)-如何使用右下角托盘图标notifyIcon

    1 拖放一个NotifyIcon控件,并设置图标,还有显示的文字   2 双击这个控件,即当最小化了主窗体,然后双击这个右下角图标的时候,要显示主窗体(大部分程序的用户体验都是这样干的,比如QQ,双击 ...

  3. Springboot项目启动报错,提示Cannot determine embedded database driver class for database type NONE

    我在springboot项目里面引入了数据库的配置: <dependency> <groupId>org.mybatis.spring.boot</groupId> ...

  4. Unity3d for beginners

    tutorial addr: https://www.youtube.com/watch?v=QUCEcAp3h28 1.打开Unity3d  File->newProject ->cre ...

  5. Java并发编程 - 基本概念

    在开始我们的并发编程前,我们必须预热一下,一些基本概念必须了解. 1. 同步(Synchronous) / 异步(Asynchronous) 同步和异步都指一次方法调用. 同步:方法开始后,调用者必须 ...

  6. Swift语言精要 - 浅谈结构体(Struct)

    CGRect, CGSize, CGPoint这些是 . String, Int, Array, Dictionary这些我们经常用的也是结构体(Struct). 那么结构体(Struct)到底是什么 ...

  7. dynamic(2) – ExpandoObject的使用

    一,ExpandoObject使用场合 在传递对象,但是又不想创建一个class或者struct的时候,ExpandoObject就是一个非常好的选择. 假如我们有一个SendMail的函数,功能是发 ...

  8. javascript设计思维

    //一.把参数当作私有变量使用 (function (a, b) { //把参数当作私有变量使用,省略了var,也节省了行数 console.log(b) //undefined,所有未赋值的变量均为 ...

  9. tcp线程聊天

    .ServerThread package serverclient; import java.io.BufferedReader; import java.io.InputStreamReader; ...

  10. XMLHttpRequest HTTP请求的返回码为0 http status = 0

    由于用户在http返回前关闭/取消,或者防火墙等原因,会造成http请求没有status信息.w3c有相应的说明:http://www.w3.org/TR/XMLHttpRequest/#the-st ...