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是 ...
随机推荐
- C#.NET常见问题(FAQ)-如何声明list的多维数组
可以用下面的方法来声明多维list数组,但是不推荐使用 //对于一维数组:List<数据类型> 变量 = new List<数据类型>(); List<int> ...
- 【转】java并发编程系列之ReadWriteLock读写锁的使用
前面我们讲解了Lock的使用,下面我们来讲解一下ReadWriteLock锁的使用,顾明思义,读写锁在读的时候,上读锁,在写的时候,上写锁,这样就很巧妙的解决synchronized的一个性能问题:读 ...
- python 3使用binascii方法的报错解决
环境是python 3 问题: 使用binascii方法一直出现报错TypeError: a bytes-like object is required, not 'str' #coding: utf ...
- http 206请求
1.概要 在客户端表明自己只需要目标URL上的部分资源的时候返回的.这种情况经常发生在客户端继续请求一个未完成的下载的时候(通常是当客户端加载一个体积较大的嵌入文件,比如视屏或PDF文件). 通常在展 ...
- 腾讯云ubuntu搭建tomcat
转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6377945.html 一:工具准备 Putty+Xftp5,见上一篇博文:http://www.cnblogs ...
- ysql怎么处理百分数? “%”
)将百分数转化为小数,再以浮点数数据类型float输入 )设置字段类型为varchar数据类型,将百分数输入为文本数据,需要计算或提取出来的时候,再转化为数值类型 //转换数据类型
- python模块之HTMLParser解析出URL链接
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python模块之HTMLParser解析出URL链接 #http://www.cnblogs.com/mf ...
- Jmeter-maven-plugin高级配置之选择测试脚本(转)
Posted on 2014 年 6 月 6 日 在pom.xml文件中可以指定运行哪些jmx脚本. 运行所有的测试脚本 Jmeter默认运行${project.base.directory}/src ...
- redis配置笔记
#cd /opt#tar -zxvf redis-4.0.6.tar.gz#cd redis-4.0.6#make #cd src#make install PREFIX=/usr/local/red ...
- 代理服务 SQUID 测试
第一部分:SQUID基础 Squid代理服务的基本配置: http_port 3128 #设置监听的IP与端口号 cache_mem 64 MB ...