Android中使用IntentService运行后台任务
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运行后台任务的更多相关文章
- Android中的IntentService
首先说下,其他概念:Android中的本地服务与远程服务是什么? 本地服务:LocalService 应用程序内部------startService远程服务:RemoteService androi ...
- iOS 和 Android 中的后台运行问题
后台机制的不同,算是iOS 和 Android的一大区别了,最近发布的iOS7又对后台处理做了一定的更改,找时间总结一下编码上的区别,先做个记录. 先看看iOS的把,首先需要仔细阅读一下Apple的官 ...
- Android中获取正在运行的应用程序-----ActivityManager.RunningAppProcessInfo类详解
今天继续讲解关于ActivityManager的使用,通过前面一节的学习,我们学会了如何利用ActivityManager获取系统里 正在运行的进程.本文要讲解的知识点是利用这些进程信息获取系统里正在 ...
- Android中获取正在运行的服务-------ActivityManager.RunningServiceInfo的使用
关于PackageManager和ActivityManager的使用 ,自己也写了一些DEMO 了,基本上写的线路参考了Settings模块下的 应用程序,大家如果真正的有所兴趣,建议大家看看源码, ...
- Android Training - 使用IntentService运行任务(Lesson 2 - 发送任务给IntentService)
写在http://hukai.me/blog/android-training-18-running-background-service-lesson-2/
- Android Training - 使用IntentService运行任务(Lesson 1 - 创建IntentService)
写在http://hukai.me/blog/android-training-18-running-background-service-lesson-1/ 版权声明:本文博客原创文章,博客,未经同 ...
- 在Android中使用并发来提高速度和性能
Android框架提供了很实用的异步处理类.然而它们中的大多数在一个单一的后台线程中排队.当你需要多个线程时你是怎么做的? 众所周知,UI更新发生在UI线程(也称为主线程).在主线程中的任何操作都会阻 ...
- [Android] Service和IntentService中显示Toast的区别
1. 表象 Service中可以正常显示Toast,IntentService中不能正常显示Toast,在2.3系统上,不显示toast,在4.3系统上,toast显示,但是不会消失. 2. ...
- 在Android中用Kotlin的Anko运行后台任务(KAD 09)
作者:Antonio Leiva 时间:Jan 19, 2017 原文链接:https://antonioleiva.com/anko-background-kotlin-android/ Anko是 ...
随机推荐
- Spring Boot中Starter是什么
比如我们要在Spring Boot中引入Web MVC的支持时,我们通常会引入这个模块spring-boot-starter-web,而这个模块如果解压包出来会发现里面什么都没有,只定义了一些POM依 ...
- Linux Centos7中MySql安装
(1) 安装Mysql5.7: 执行命令:rpm -ivh http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64/mysql-co ...
- HttpLuaModule——翻译(一)
最近经常使用春哥和小哲老师写的NGINX-LUA,非常苦于没有中文文档,特别是向我这种英文水平实在有限的同学,所以将遇到的模块记录下来,供以后参考!原文:http://wiki.nginx.org/H ...
- ES6 新增数据类型检测 Set Map Proxy
检测代码方法 function isNative(api){ return /native code/.test(api.toString())&&typeof api !== 'un ...
- Maven依赖传递、依赖传递排除、依赖冲突
转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6628429.html 一:Maven依赖传递 假如有Maven项目A,项目B依赖A,项目C依赖B.那么我们可 ...
- postgresql修改配置生效方法
对于配置服务器,,太多时候我们在Linux中做的操作是,配置*.conf文件,然后重启服务.而很多服务都具有reload功能,而但是具体到某个配置,有时候直接说出需不需要重启服务而使得配置生效,这并不 ...
- Java通过Fork/Join来优化并行计算
Java代码: package Threads; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Recur ...
- fiddlescript 操作
什么是 JScript .NET Fiddler Script 是用JScript.NET语言写的 http://docs.telerik.com/fiddler/KnowledgeBase/Fidd ...
- ASP.NET 动态查找数据 并且生成xml文档 同时使用xslt转换为xhtml
前言 xsl是一门标签解析语言,很适合做动态网页的前台标签 www.bamn.cn 1 首先是aspx页面 添加一个输入框 按钮 还有一个用来显示解析后的xhtml代码的控件 <form id= ...
- Kibana 日志查询
1 概述 很多系统的日志都会放在 Kibana 供查询,就是所谓的 ELK.Kibana 除了可以使用界面供的一些 tab 或者 button 去筛选日志,也可以在搜索栏中使用 Lucene 的语法简 ...