四大组件之特殊Service(IntentService)的使用
来源:互联网 发布:子弹图纸尺寸图片编程 编辑:程序博客网 时间:2024/04/30 09:24
在Service中,通常是不需要同时处理多个请求的,在这种情况下,使用IntentService或许是最好的选择。为什么呢?下面的这个问题给出了答案。
IntentService如何使用?和Service有什么区别?
IntentService里面是默认自带一条线程的,无需自己去new子线程,而且是和主线程分离的,使用的时候只需要处理onHandleIntent()这个方法即可。不需要去写onCreate(),也不需要去写onStartCommand(),而且在任务执行结束后,会自行调用stopSelf()方法来关闭Service。IntentService适用于单线程去完成任务,而且不会阻塞主线程。
MainActivity代码,很简单,启动Service:
package com.example.lenovo.demo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * 开启服务,进行下载 */ public void downLoad(View view){ startService(new Intent(this,MyService.class)); }}
MyService代码:
package com.example.lenovo.demo;import android.app.IntentService;import android.content.Intent;/** * Created by shan on 2016/7/23. * */public class MyService extends IntentService { /** * Creates an IntentService. Invoked by your subclass's constructor. * 这里需要一个空的构造方法 */ public MyService() { super(""); } @Override protected void onHandleIntent(Intent intent) { //无需new子线程,直接进行耗时操作:do something //任务完成后也无需关闭Service,源码内部已经实现stopSelf() }}
最后,配置清单文件,静态注册Service,添加所需的权限即可。具体的耗时代码就不写了~~
0 0
- 四大组件之特殊Service(IntentService)的使用
- Android 四大组件之特殊Service(IntentService)的使用
- 四大组件之一Service——应用实例二(IntentService类的使用)
- Android四大组件之Service的使用
- 四大组件之普通Service的使用
- android四大组件之Service和子类IntentService
- Android 四大组件之一:Service后台服务之IntentService
- [Android知识体系]之四大组件:service(intentService)
- Android 四大组件之Service 的生命周期和使用
- android四大组件学习之-Service的使用
- Android 四大组件之Service的基本使用
- Android 四大组件之Service 的生命周期和使用
- Android四大组件之Service的两种使用情况
- 四大组件之Service
- 四大组件之Service
- 四大组件之Service
- 四大组件之Service
- 四大组件之Service
- POJ 2553The Bottom of a Graph
- android 子线程中更新界面?被ProgressBar给迷惑了
- Nova 是如何统计 OpenStack 计算资源
- 平衡搜索树之AVLTree
- Ekka Dokka
- 四大组件之特殊Service(IntentService)的使用
- Busybox 登陆后如何设置是否需要用户名和密码进入文件系统
- 【VS开发】【图像处理】RGB各种格式
- 关于海量数据查找排序问题
- Spark MLlib之分类模型源码分析
- 挑战这十七项编程 锻炼大脑并且提升能力
- hdu1015 Safecracker (DFS)
- 设计模式六大原则(5):迪米特法则
- 堆和栈的区别(转过无数次的文章)