分类:C#、Android、VS2015;

创建日期:2016-03-01

一、简介

为了进一步简化Intent过滤器的用法,Android系统又提供了一个IntentService类,这样一来,你也不需要重写其他的方法了,直接实现一个继承自IntentService的类,然后重写OnHandleIntent方法即可。

IntentService类继承自Service类。这个类自动使用工作线程处理所有Service的启动请求(即:对IntentService的每次请求都会自动启动一个线程去处理它)。

因为大多数started服务都不需要“并发”处理多个请求(这实际上是一个危险的多线程情况),所以最佳方式也许就是用IntentService类来实现你的服务。

总之,只要Started Service不需要“并发”处理多个请求,首选的办法就是用IntentService来实现。

1、IntentService的工作机制

IntentService将自动执行以下步骤:

创建一个缺省的工作(worker)线程,它独立于应用程序主线程来执行所有发送到OnStartCommand方法的intent。

创建一个工作队列,每次向你的OnHandleIntent()传入一个intent,这样你就永远不必担心多线程问题了。

在处理完所有的启动请求后,终止服务,因此你就永远不需调用StopSelf方法了。

提供缺省的OnBind()实现代码,它返回null。

提供缺省的OnStartCommand()实现代码,它把intent送入工作队列,稍后会再传给你的OnHandleIntent()实现代码。

以上所有步骤将汇成一个结果:你要做的全部工作就是实现OnHandleIntent()完成客户端提交的任务。(当然你还需要为服务提供一小段构造方法。)

2、实现OnHandleIntent方法

实现IntentService请求的代码很简单,你要做的工作就是在自定义的继承自IntentService类中重写OnHandleIntent()方法即可,它会自动接收每个启动请求的intent,然后自动在后台完成Intent请求的工作。

下面的代码演示了如何重写OnHandleIntent()方法:

  1. [Service]
  2. [IntentFilter(new string[]{"com.xamarin.DemoIntentService"})]
  3. public class DemoIntentService: IntentService
  4. {
  5. public DemoIntentService () : base("DemoIntentService")
  6. {
  7. }
  8.  
  9. protected override void OnHandleIntent (Android.Content.Intent intent)
  10. {
  11. Console.WriteLine ("perform some long running work");
  12. Console.WriteLine ("work complete");
  13. }
  14. }

继承自IntentService的类与继承自Service的自定义类的区别是:继承自IntentService的类需要通过构造函数传递给基类一个字符串,该字符串的作用是标识内部工作线程。

从内部实现代码上来看,IntentService实际上就是把每个Intent发送的请求都放到一个工作队列中,然后分别在不同的线程中处理工作队列中的每个请求,由于这些Intent都是在与主线程不同的单独线程中运行的,当然不会阻止主线程的运行。

当某个Intent处理完后,IntentService会立即自动调用StopSelf方法停止这个Intent。

总之,利用IntentService,我们既不需要在服务中去显式创建单独的线程,也不需要在重写的Ondestroy方法中终止自己创建的线程,这一些都由IntentService类去自动实现,你只需要关注在服务中实现的功能就行了。

二、示例3--IndentServiceDemo

运行截图

  

主要设计步骤

(1)添加ch1603_Main.axml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <Button
  7. android:id="@+id/ch1603StartService"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="启动服务" />
  11. <Button
  12. android:id="@+id/ch1603StopService"
  13. android:layout_width="fill_parent"
  14. android:layout_height="wrap_content"
  15. android:text="停止服务" />
  16. </LinearLayout>

(2)添加ch1603ServiceDemo.cs

  1. using System;
  2. using Android.App;
  3. using Android.Content;
  4. using Android.OS;
  5. using Android.Widget;
  6. using System.Threading;
  7.  
  8. namespace MyDemos.SrcDemos
  9. {
  10. [Service]
  11. [IntentFilter(new string[] { action })]
  12. public class ch1603ServiceDemo : IntentService
  13. {
  14. public const string action = "MyDemos.ch1603Service";
  15.  
  16. public ch1603ServiceDemo() : base("ch1603ServiceDemo")
  17. {
  18. }
  19.  
  20. protected override void OnHandleIntent(Intent intent)
  21. {
  22. var myHandler = new Handler(MainLooper);
  23. myHandler.Post(() =>
  24. {
  25. Toast.MakeText(this, "服务已启动", ToastLength.Short).Show();
  26. });
  27. for (int i = 1; i <= 10; i++)
  28. {
  29. var msg = string.Format("这是来自服务的第{0}个消息", i);
  30. Thread.Sleep(TimeSpan.FromSeconds(4));
  31. myHandler.Post(() =>
  32. {
  33. Toast.MakeText(this, msg, ToastLength.Short).Show();
  34. });
  35. }
  36. }
  37.  
  38. public override void OnDestroy()
  39. {
  40. base.OnDestroy();
  41. new Handler(MainLooper).Post(() =>
  42. {
  43. Toast.MakeText(this, "服务已停止", ToastLength.Short).Show();
  44. });
  45. }
  46. }
  47. }

(3)添加ch1603MainActivity.cs

  1. using Android.App;
  2. using Android.Content;
  3. using Android.OS;
  4. using Android.Widget;
  5.  
  6. namespace MyDemos.SrcDemos
  7. {
  8. [Activity(Label = "ch1603MainActivity")]
  9. public class ch1603MainActivity : Activity
  10. {
  11. protected override void OnCreate(Bundle savedInstanceState)
  12. {
  13. base.OnCreate(savedInstanceState);
  14. SetContentView(Resource.Layout.ch1603_Main);
  15. var start = FindViewById<Button>(Resource.Id.ch1603StartService);
  16. start.Click += delegate
  17. {
  18. StartService(new Intent(ch1603ServiceDemo.action));
  19. };
  20.  
  21. var stop = FindViewById<Button>(Resource.Id.ch1603StopService);
  22. stop.Click += delegate
  23. {
  24. StopService(new Intent(ch1603ServiceDemo.action));
  25. };
  26. }
  27. }
  28. }

【Android】16.4 IntentService类的更多相关文章

  1. Android 进阶16:IntentService 使用及源码解析

    It's time to start living the life you've only imagined. 读完本文你将了解: IntentService 简介 IntentService 源码 ...

  2. 用.Net打造一个移动客户端(Android/IOS)的服务端框架NHM(四)——Android端Http访问类(转)

    本章目的 在上一章中,我们利用Hibernate Tools完成了Android Model层的建立,依赖Hibernate Tools的强大功能,自动生成了Model层.在本章,我们将继续我们的项目 ...

  3. 29个android开发常用的类、方法及接口

    在安卓开发中,我们常常都需要借助各种各样的方法.类和接口来实现相关功能.提升开发效率,但对于初学者而言,什么时候该用什么类.方法和接口呢?下面小编整理了29个,日常开发中比较常用的类.方法.接口及其应 ...

  4. (转载)实例详解Android快速开发工具类总结

    实例详解Android快速开发工具类总结 作者:LiJinlun 字体:[增加 减小] 类型:转载 时间:2016-01-24我要评论 这篇文章主要介绍了实例详解Android快速开发工具类总结的相关 ...

  5. Top 16 Java 应用类 - 这些功能再也不用自己写了

    Java中有很多应用类.这些类定义静态方法能够解决非常多常见的问题.以下是通过5万个开源项目统计得到的最热门的16个应用类. 类按热门程序排列.类的方法也是按热门程序排序. 浏览这个类能够看看有哪些功 ...

  6. Android 通过 Intent 传递类对象或list对象

    (转:http://www.cnblogs.com/shaocm/archive/2013/01/08/2851248.html) Android中Intent传递类对象提供了两种方式一种是 通过实现 ...

  7. 命令行下使用javah命令生成.h文件,出现“错误: 无法访问android.app.Activity 找不到android.app.Activity的类文件”的解决方法

    在学习NDK中,当我在项目的bin/classes目录下使用javah命令生成头文件时,出现了“错误: 无法访问android.app.Activity 找不到android.app.Activity ...

  8. android SQLite使用SQLiteOpenHelper类对数据库进行操作

    android SQLite使用SQLiteOpenHelper类对数据库进行操作 原文: http://byandby.iteye.com/blog/835580

  9. Android 通过 Intent 传递类对象

    Android中Intent传递类对象提供了两种方式一种是 通过实现Serializable接口传递对象,一种是通过实现Parcelable接口传递对象. 要求被传递的对象必须实现上述2种接口中的一种 ...

随机推荐

  1. less 命令(转)

    原文:http://www.cnblogs.com/peida/archive/2012/11/05/2754477.html less 工具也是对文件或其它输出进行分页显示的工具,应该说是linux ...

  2. spring jdbc连接数据库

    1.在applicationContext.xml中配置jdbc bean <bean id="dataSource" class="org.springframe ...

  3. 在webBrowser1.Navigate(url)中设置Cookie的注意点

    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] public static exte ...

  4. eclipse Java代码折叠工具

      eclipse Java代码折叠工具 CreateTime--2018年5月17日15点09分 Author:Marydon 1.问题描述 eclipse自带的代码折叠工具,无法折叠try{}ca ...

  5. 〖Linux〗Ubuntu 64位安装sqlite3_analyzer

    1. 安装过程 -dev:i386 wget -c "http://www.sqlite.org/2013/sqlite-analyzer-linux-x86-3080200.zip&quo ...

  6. Python之str方法

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #Python之str方法 #http://python.jobbole.com/82655/ #str为一个 ...

  7. 生产服务器环境最小化安装后 Centos 6.5优化配置备忘

    生产服务器环境最小化安装后 Centos 6.5优化配置备忘 作者:Memory 发布于:2014-8-13 15:00 Wednesday 服务器 本文 centos 6.5 优化 的项有18处: ...

  8. oracle10-11数据库下载

    Oracle数据库官方下载,需要注册oracle账号,方可下载! 11G 7个压缩包含义: p102025301120——Linux-x86-64_1of7.zip             datab ...

  9. jQuery+PHP动态显示(项目)实时时间和倒计时

    jQuery动态显示当前时间:    html代码:<div id="current_time"></div> setInterval()使用:setInt ...

  10. 如何在Win8中设置虚拟热点共享上网(转)

    摘自:http://www.enet.com.cn/article/2013/0408/A20130408273749.shtml 在Windows 7中,我们可以通过网络与共享中心的“设置新的连接和 ...