Android Service总结05 之IntentService
Android Service总结05 之IntentService
版本 |
版本说明 |
发布时间 |
发布人 |
V1.0 |
添加了IntentService的介绍和示例 |
2013-03-17 |
Skywang |
1 IntentService介绍
IntentService继承与Service,它最大的特点是对服务请求逐个进行处理。当我们要提供的服务不需要同时处理多个请求的时候,可以选择继承IntentService。
IntentService有以下特点:
(1) 它创建了一个独立的工作线程来处理所有的通过onStartCommand()传递给服务的intents。
(2) 创建了一个工作队列,来逐个发送intent给onHandleIntent()。
(3) 不需要主动调用stopSelft()来结束服务。因为,在所有的intent被处理完后,系统会自动关闭服务。
(4) 默认实现的onBind()返回null
(5) 默认实现的onStartCommand()的目的是将intent插入到工作队列中。
继承IntentService的类至少要实现两个函数:构造函数和onHandleIntent()函数。要覆盖IntentService的其它函数时,注意要通过super调用父类的对应的函数。
2 IntentService示例
示例说明:编写一个activity,包含2个按钮和1个进度条,2个按钮分别是开始按钮、结束按钮。点击“开始”按钮:进度条开始加载;“开始”变成“重启”按钮;显示“结束”按钮(默认情况,“结束”按钮是隐藏状态)。
IntentService的示例包括2个类:
IntentServiceSub.java —— 继承IntentService,并新建一个线程,用于每隔200ms将一个数字+2,并通过广播发送出去。
IntentServiceTest.java —— 启动IntentServiceSub服务,接收它发送的广播,并根据广播中的数字值来更新进度条。
IntentServiceSub.java的内容如下:
- package com.test;
- import android.app.IntentService;
- import android.content.Intent;
- import android.util.Log;
- import java.lang.Thread;
- /**
- * @desc IntentService的实现类:每隔200ms将一个数字+2并通过广播发送出去
- * @author skywang
- *
- */
- public class IntentServiceSub extends IntentService {
- private static final String TAG = "skywang-->IntentServiceTest";
- // 发送的广播对应的action
- private static final String COUNT_ACTION = "com.test.COUNT_ACTION";
- // 线程:用来实现每隔200ms发送广播
- private static CountThread mCountThread = null;
- // 数字的索引
- private static int index = 0;
- public IntentServiceSub() {
- super("IntentServiceSub");
- Log.d(TAG, "create IntentServiceSub");
- }
- @Override
- public void onCreate() {
- Log.d(TAG, "onCreate");
- super.onCreate();
- }
- @Override
- public void onDestroy() {
- Log.d(TAG, "onDestroy");
- super.onDestroy();
- }
- @Override
- protected void onHandleIntent(Intent intent) {
- Log.d(TAG, "onHandleIntent");
- // 非首次运行IntentServiceSub服务时,执行下面操作
- // 目的是将index设为0
- if ( mCountThread != null) {
- index = 0;
- return;
- }
- // 首次运行IntentServiceSub时,创建并启动线程
- mCountThread = new CountThread();
- mCountThread.start();
- }
- private class CountThread extends Thread {
- @Override
- public void run() {
- index = 0;
- try {
- while (true) {
- // 将数字+2,
- index += 2;
- // 将index通过广播发送出去
- Intent intent = new Intent(COUNT_ACTION);
- intent.putExtra("count", index);
- sendBroadcast(intent);
- // Log.d(TAG, "CountThread index:"+index);
- // 若数字>=100 则退出
- if (index >= 100) {
- if ( mCountThread != null)
- mCountThread = null;
- return ;
- }
- // 200ms
- this.sleep(200);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
IntentServiceTest.java的内容如下:
- package com.test;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ProgressBar;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.content.Context;
- import android.content.BroadcastReceiver;
- import android.util.Log;
- /**
- * @desc 创建一个activity,包含2个按钮(开始/结束)和1个ProgressBar
- * 点击“开始”按钮,显示“结束”按钮,并启动ProgressBar。
- * 点击“结束”按钮,结束ProgressBar的进度更新
- * @author skywang
- *
- */
- public class IntentServiceTest extends Activity {
- /** Called when the activity is first created. */
- private static final String TAG = "skywang-->IntentServiceTest";
- private static final String COUNT_ACTION = "com.test.COUNT_ACTION";
- private CurrentReceiver mReceiver;
- private Button mStart = null;
- private Button mStop = null;
- private Intent mIntent = null;
- private Intent mServiceIntent = new Intent("com.test.subService");
- private ProgressBar mProgressBar = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.intent_service_test);
- mStart = (Button) findViewById(R.id.start);
- mStart.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- Log.d(TAG, "click start button");
- // 显示“结束”按钮
- mStop.setVisibility(View.VISIBLE);
- // 将“开始”按钮更名为“重启”按钮
- mStart.setText(R.string.text_restart);
- // 启动服务,用来更新进度
- if (mServiceIntent == null)
- mServiceIntent = new Intent("com.test.subService");
- startService(mServiceIntent);
- }
- });
- mStop = (Button) findViewById(R.id.stop);
- mStop.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- Log.d(TAG, "click stop button");
- if (mServiceIntent != null) {
- // 结束服务。
- // 注意:实际上这里并没有起效果。因为IntentService的特性所致。
- // IntentService的声明周期特别段,在startService()启动后,立即结束;所以,
- // 再调用stopService()实际上并没有起作用,因为服务已经结束!
- stopService(mServiceIntent);
- mServiceIntent = null;
- }
- }
- });
- mStop.setVisibility(View.INVISIBLE);
- mProgressBar = (ProgressBar) findViewById(R.id.pbar_def);
- // 隐藏进度条
- mProgressBar.setVisibility(View.INVISIBLE);
- // 动态注册监听COUNT_ACTION广播
- mReceiver = new CurrentReceiver();
- IntentFilter filter = new IntentFilter();
- filter.addAction(COUNT_ACTION);
- this.registerReceiver(mReceiver, filter);
- }
- @Override
- public void onDestroy(){
- super.onDestroy();
- if(mIntent != null)
- stopService(mIntent);
- if(mReceiver != null)
- this.unregisterReceiver(mReceiver);
- }
- /**
- * @desc 更新进度条
- * @param index
- */
- private void updateProgressBar(int index) {
- int max = mProgressBar.getMax();
- if (index < max) {
- // 显示进度条
- mProgressBar.setVisibility(View.VISIBLE);
- mProgressBar.setProgress(index);
- } else {
- // 隐藏进度条
- mProgressBar.setVisibility(View.INVISIBLE);
- // 隐藏“结束”按钮
- mStop.setVisibility(View.INVISIBLE);
- // 将“重启”按钮更名为“开始”按钮
- mStart.setText(R.string.text_start);
- }
- // Log.d(TAG, "progress : "+mProgressBar.getProgress()+" , max : "+max);
- }
- /**
- * @desc 广播:监听COUNT_ACTION,获取索引值,并根据索引值来更新进度条
- * @author skywang
- *
- */
- private class CurrentReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- if (COUNT_ACTION.equals(action)) {
- int index = intent.getIntExtra("count", 0);
- updateProgressBar(index);
- }
- }
- }
- }
layout文件intent_service_test.xml的内容如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- >
- <LinearLayout
- android:orientation="horizontal"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <Button
- android:id="@+id/start"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/text_start"
- />
- <Button
- android:id="@+id/stop"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/text_stop"
- />
- </LinearLayout>
- <ProgressBar
- android:id="@+id/pbar_def"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- style="@android:style/Widget.ProgressBar.Horizontal"
- android:max="100"
- android:progress="0"
- />
- </LinearLayout>
manifest代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.test"
- android:versionCode="1"
- android:versionName="1.0">
- <uses-sdk android:minSdkVersion="8" />
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity
- android:name=".IntentServiceTest"
- android:screenOrientation="portrait"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <service android:name=".IntentServiceSub">
- <intent-filter>
- <action android:name="com.test.subService" />
- </intent-filter>
- </service>
- </application>
- </manifest>
点击下载:示例源代码
程序截图如下:
更多service内容:
2 Android Service总结02 service介绍
3 Android Service总结03 之被启动的服务 -- Started Service
4 Android Service总结04 之被绑定的服务 -- Bound Service
5 Android Service总结05 之IntentService
参考文献:
1,Android API文档: http://developer.android.com/guide/components/services.html
Android Service总结05 之IntentService的更多相关文章
- Android Service总结06 之AIDL
Android Service总结06 之AIDL 版本 版本说明 发布时间 发布人 V1.0 初始版本 2013-04-03 Skywang 1 AIDL介绍 AIDL,即And ...
- Android Service总结04 之被绑定的服务 -- Bound Service
Android Service总结04 之被绑定的服务 -- Bound Service 版本 版本说明 发布时间 发布人 V1.0 添加了Service的介绍和示例 2013-03-17 Skywa ...
- Android Service总结01 目录
Android Service总结01 目录 1 Android Service总结01 目录 2 Android Service总结02 service介绍 介绍了“4种service 以及 它们的 ...
- Android Service总结02 service介绍
Android Service总结02 service介绍 版本 版本说明 发布时间 发布人 V1.0 介绍了Service的种类,常用API,生命周期等内容. 2013-03-16 Skywang ...
- Android Service总结03 之被启动的服务 -- Started Service
Android Service总结03 之被启动的服务 -- Started Service 版本 版本说明 发布时间 发布人 V1.0 添加了Service的介绍和示例 2013-03-17 Sky ...
- android服务Service(上)- IntentService
Android学习笔记(五一):服务Service(上)- IntentService 对于需要长期运行,例如播放音乐.长期和服务器的连接,即使已不是屏幕当前的activity仍需要运行的情况,采用服 ...
- android service 的各种用法(IPC、AIDL)
http://my.oschina.net/mopidick/blog/132325 最近在学android service,感觉终于把service的各种使用场景和用到的技术整理得比较明白了,受益颇 ...
- 2、android Service 详细用法
定义一个服务 在项目中定义一个服务,新建一个ServiceTest项目,然后在这个项目中新增一个名为MyService的类,并让它继承自Service,完成后的代码如下所示: ? 1 2 3 4 5 ...
- Android组件系列----Android Service组件深入解析
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
随机推荐
- 20155301PC平台逆向破解
20155301PC平台逆向破解 1.掌握NOP, JNE, JE, JMP, CMP汇编指令的机器码 NOP:NOP指令即"空指令".执行到NOP指令时,CPU什么也不做,仅仅当 ...
- 20155338《网络对抗》Exp3 免杀原理与实践
20155338<网络对抗>Exp3 免杀原理与实践 实验过程 一.免杀效果参考基准 Kali使用上次实验msfvenom产生后门的可执行文件,上传到老师提供的网址http://www.v ...
- python 回溯法 子集树模板 系列 —— 9、旅行商问题(TSP)
问题 旅行商问题(Traveling Salesman Problem,TSP)是旅行商要到若干个城市旅行,各城市之间的费用是已知的,为了节省费用,旅行商决定从所在城市出发,到每个城市旅行一次后返回初 ...
- 利用fiddler core api 拦截修改 websocket 数据
一般的中间人攻击基本都是拦截修改普通的http协议里面的内容,而对于怎么拦截修改websocket协议传输的内容好像都没有多少介绍. talk is cheap show me the code us ...
- ReactJS实用技巧(2):从新人大坑——表单组件来看State
不太清楚有多少初学React的同学和博主当时一样,在看完React的生命周期.数据流之后觉得已经上手了,甩开文档啪啪啪的开始敲了起来.结果...居然被一个input标签给教做人了. 故事是这样的:首先 ...
- Android 测试之Monkey
一.什么是Monkey Monkey是Android中的一个命令行工具,可以运行在模拟器里或实际设备中.它向系统发送伪随机的用户事件流(如按键输入.触摸屏输入.手势输入等),实现对正在开发的应用程序进 ...
- 关于UGUI不拦截射线的方法
起因:开发游戏,要在设置界面里给一个设置项添加一个东西解释这个项是干啥的,要求鼠标移到文字上的时候显示一个弹窗差不多的东西,见动图,鼠标移开会消失.但是当我移动鼠标到弹窗上的时候,UGUI会发射一根射 ...
- CEPH LIO iSCSI Gateway
参考文档: Ceph Block Device:http://docs.ceph.com/docs/master/rbd/ CEPH ISCSI GATEWAY:http://docs.ceph.co ...
- 红黑树插入与删除完整代码(dart语言实现)
之前分析了红黑树的删除,这里附上红黑树的完整版代码,包括查找.插入.删除等.删除后修复实现了两种算法,均比之前的更为简洁.一种是我自己的实现,代码非常简洁,行数更少:一种是Linux.Java等源码版 ...
- Notes of Daily Scrum Meeting(12.16)
最近好几门课的大作业都到了要截止的时候了,好多天队员们都抽不出来时间做软工的项目了,这样确实 和我们的计划出入很大,不过希望老师谅解,三门课程设计确实压力很大. 今天的团队任务总结如下: 团队成员 今 ...