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是 ...
随机推荐
- iOS 获取设备型号 ip6更新
//获得设备型号 + (NSString *)getCurrentDeviceModel:(UIViewController *)controller { ]; size_t len; char *m ...
- Unity3D 学习 创建简单的按钮、相应事件
选择file -->new project 然后保存到相应的地方 下面是这个刚创建的工程效果图. 然后创建一个C# Script ||定位到最左下角找到 assets --> creat ...
- javascript基于原型的语言的特点
一.基于原型的语言的特点 1 只有对象,没有类;对象继承对象,而不是类继承类. 2 “原型对象”是基于原型语言的核心概念.原型对象是新对象的模板,它将自身的属性共享给新对象.一个对象不但可以享有自己 ...
- dom4j解析以及生成xml字符串测试
public static void main(String[] args) { String xmlStr = "<ybjcVo>"+ "<zbGri ...
- oneinstack一键部署linux生产环境那点事(ubuntu)
http://oneinstack.com/install/ (1)将oneinstack-full.tar.gz最新版安装文件上传至/usr/local/下 (2)解压tar xzvf oneins ...
- UBUNTU 字符界面来回切换
图形界面切换到字符界面: 实体机:Ctrl + Alt + F1 VMware虚拟机:按下ALT+CTRL+SPACE(空格),ALT+CTRL不松开,再按F1.这样就可以切换到字符界面 字符界面切换 ...
- HttpLuaModule——翻译(一)
最近经常使用春哥和小哲老师写的NGINX-LUA,非常苦于没有中文文档,特别是向我这种英文水平实在有限的同学,所以将遇到的模块记录下来,供以后参考!原文:http://wiki.nginx.org/H ...
- 跟踪 Ring3 - Ring0 的运行流程
理论知识 SYSENTER 指令是在 Inter Pentium(R) Ⅱ 处理器上作为"高速系统调用"功能的一部分被首次引用的. SYSENTER 指令进行过专门的优化,能够以最 ...
- NameNode重新格式化以后DataNode不能启动
最近重新格式化NameNode以后,发现几个DataNode都不能启动了. 这是因为dfs.name.dir路径下面有一个current/VERSION文件,里面有一个clusterID,重新格式化以 ...
- auto function -> return type 当不能从{}内推断类型时
示例: template<class F, class... Args> auto ThreadPool::enqueue(F&& f, Args&&... ...