通过前两篇文章的学习,我们知道了服务的代码是默认运行在主线程里的,因此,如果要在服务里面执行耗时操作的代码,我们就需要开启一个子线程去处理这些代码。比如我们可以在 onStartCommand方法里面开启子线程来处理耗时代码。

  1. public int onStartCommand(Intent intent, int flags, int startId) {
  2.  
  3. Thread thread = new Thread(){
  4. @Override
  5. public void run() {
  6.  
  7. /**
  8. * 耗时的代码在子线程里面写
  9. */
  10.  
  11. }
  12. };
  13. thread.start();
  14.  
  15. return super.onStartCommand(intent, flags, startId);
  16. }

但是,我们都知道,服务一旦启动,就会一直运行下去,必须调用stopService()或者stopSelf()方法才能让服务停止下来。所以,我们来修改一下run方法

  1. public void run() {
  2.  
  3. /**
  4. * 耗时的代码在子线程里面写
  5. */
  6. stopSelf();
  7.  
  8. }

就这样,我们很容易的就在服务里面开启了一个线程,然后在代码最后面加上stopSelf();这样就可以在代码运行结束的时候,结束服务了。但是这样对于我们开发者来说,是不是有些麻烦呢,确实有点麻烦,比如你有时候忘记了开启线程呢?或者忘记了调用stopSelf()?所以,谷歌给我们一个很好的类,通过这个类我们就可以不用管这些东西,因为这个类已经帮我们实现了在子线程中操作代码了。同时,但子线程代码执行完毕,这个服务会自动销毁,不用再占用内存资源。所以,我们通过这个类,就可以不用去开启线程,也不用去销毁这个服务。因为,这个类都帮我们处理好了。这个类就是IntentService。这个类的使用和Service大同小异,但是比Service更加省心,更加方便。下面我们直接看代码吧,我习惯在代码中讲解。

布局文件就是一个按钮而已,先看布局。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6.  
  7. <Button
  8. android:id="@+id/bt_start"
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. />
  12.  
  13. </LinearLayout>

intentservice.xml

和Service一样,使用的话,要在清单文件中

  1. <service android:name="com.example.mydemo.intentservice.MyIntentService"></service>

然后是服务类

  1. package com.example.mydemo.intentservice;
  2.  
  3. import android.annotation.SuppressLint;
  4. import android.app.IntentService;
  5. import android.content.Intent;
  6. import android.os.Handler;
  7. import android.os.Message;
  8. import android.widget.Toast;
  9.  
  10. /**
  11. ***************************************************************
  12. *
  13. * @版权 LinFeng
  14. *
  15. * @作者 LinFeng
  16. *
  17. * @版本 1.0
  18. *
  19. * @创建日期 2016-6-10
  20. *
  21. * @功能描述
  22. *****************************************************************
  23. */
  24.  
  25. /**
  26. * 注意,继承的是 IntentService而不是Service哦,还有,既然是服务,那么就必须在清单文件里面注册
  27. */
  28. public class MyIntentService extends IntentService {
  29.  
  30. @SuppressLint("HandlerLeak")
  31. Handler handler = new Handler(){
  32.  
  33. @Override
  34. public void handleMessage(Message msg) {
  35. Toast.makeText(MyIntentService.this, "IntetnService Running", Toast.LENGTH_SHORT)
  36. .show();
  37. super.handleMessage(msg);
  38.  
  39. }
  40. };
  41.  
  42. /**
  43. * 使用Eclipse如果没有添加这个无参构造函数的话会报一个运行时错误: java.lang.InstantiationException
  44. */
  45. public MyIntentService() {
  46. /**
  47. * 这里只需要传入一个字符串就可以了
  48. */
  49. super("MyIntentService");
  50.  
  51. }
  52.  
  53. /**
  54. * 必须实现的抽象方法,我们的业务逻辑就是在这个方法里面去实现的 在这个方法里实现业务逻辑,我们就不用去关心ANR的问题
  55. */
  56. @Override
  57. protected void onHandleIntent(Intent intent) {
  58.  
  59. /**
  60. * 因为这个方法是在子线程里面处理的,所以这里我们不能直接在子线程里面弹Toast
  61. * 我们这里使用handler来帮助我们处理Toast
  62. */
  63. handler.sendEmptyMessage(0);
  64. }
  65.  
  66. /**
  67. * 为了验证onHandleIntent执行后,服务会不会自动销毁,我们在这里重写onDestroy方法
  68. * 如果会自动销毁,那么在"IntetnService Running"出现后,应该会出现"IntetnService Stop"
  69. */
  70. @Override
  71. public void onDestroy() {
  72. super.onDestroy();
  73. Toast.makeText(this, "IntetnService Stop", Toast.LENGTH_SHORT).show();
  74. }
  75.  
  76. }

MyIntentService

然后就是主界面类,主界面类也没干啥事情,就是按钮点击事件,点击后启动服务,启动IntentService和启动普通的Service没有差别,都是通过意图来启动的。

  1. package com.example.mydemo.intentservice;
  2.  
  3. import com.example.mydemo.R;
  4.  
  5. import android.app.Activity;
  6. import android.content.Intent;
  7. import android.os.Bundle;
  8. import android.view.View;
  9. import android.view.View.OnClickListener;
  10. import android.widget.Button;
  11.  
  12. /**
  13. ***************************************************************
  14. *
  15. * @版权 LinFeng
  16. *
  17. * @作者 LinFeng
  18. *
  19. * @版本 1.0
  20. *
  21. * @创建日期 2016-6-10
  22. *
  23. * @功能描述
  24. *****************************************************************
  25. */
  26. public class IntentServiceActivity extends Activity{
  27.  
  28. private Button btButton;
  29. @Override
  30. protected void onCreate(Bundle savedInstanceState) {
  31. super.onCreate(savedInstanceState);
  32. setContentView(R.layout.intentservice);
  33.  
  34. btButton = (Button) findViewById(R.id.bt_start);
  35. btButton.setText("Start IntentService");
  36.  
  37. btButton.setOnClickListener(new OnClickListener() {
  38.  
  39. @Override
  40. public void onClick(View v) {
  41. Intent intent = new Intent(IntentServiceActivity.this,MyIntentService.class);
  42. startService(intent);
  43. }
  44. });
  45. }
  46.  
  47. }

IntentServiceActivity

然后就是运行截图了

更加省心的服务,IntentService的使用的更多相关文章

  1. 服务 IntentService 前台服务 定时后台服务

    Activity public class MainActivity extends ListActivity {     private int intentNumber = 0;     @Ove ...

  2. 23 服务IntentService Demo6

    MainActivity.java package com.qf.day23_service_demo2; import android.app.Activity; import android.co ...

  3. IntentService 服务 工作线程 stopself MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  4. Android服务(Service)研究

    Service是android四大组件之一,没有用户界面,一直在后台运行. 为什么使用Service启动新线程执行耗时任务,而不直接在Activity中启动一个子线程处理? 1.Activity会被用 ...

  5. android service服务的学习

    1.Service简单概述   Service(服务)是一个一种可以在后台执行长时间运行操作而没有用户界面的应用组件.服务可由其他应用组件启动(如Activity),服务一旦被启动将在后台一直运行,即 ...

  6. Service基础使用

    Service基础使用 之前的文章一直介绍Activity的使用,很多知识和用法单一的配合Activity使用,这次将总结Android四大组件之二--Service. 本文将要介绍以下内容: Ser ...

  7. Android Service提高

    我们从以下几个方面来了解Service IntentService的使用 Service与Thread的区别 Service生命周期 前台服务 服务资源被系统以外回收处理办法 不被销毁的服务 Inte ...

  8. Android--Service之提高

    前言 上一篇博客讲解了一下Android下Service组件的基本使用,对Service组件还不了解的朋友可以先去看看另外一篇Service基础的博客:Android--Service之基础.这篇博客 ...

  9. Android——Service介绍与例子

    官方定义:Service(服务)是一个没有用户界面的在后台运行执行耗时操作的应用组件.其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行.另外,一个组件 ...

随机推荐

  1. Hibernate中使用Spring Data JPA

    一.配置文件的方式 1.pom.xml中引入相关依赖 <properties> <project.build.sourceEncoding>UTF-8</project. ...

  2. 配置标准的 ActiveMQ 组件

    简单地说,使用 ActiveMQ 的方式是固定且直接的:启动 ActiveMQ 服务器,发送消息,接收消息.但你并未理解 ActiveMQ 背后运作的详情.在一些要求更高的场景里,需要理解并有能力自定 ...

  3. 2017-03-04 dotnet core网站发布到Linux系统中

    今天开始学习dotnet core的开发,距离Visual Stuio 2017正式版的发布,也就是VS20周岁的生日还有三天,在我的电脑上安装的是VS2017 Enterprise RC版, 在VS ...

  4. 安装Babel(命令行环境,针对Babel6.x版本)

    1.首先安装babel-cli(用于在终端使用babel) npm install -g babel-cli 2.然后安装babel-preset-es2015插件 npm install --sav ...

  5. centos下环境变量配置

    export JAVA_HOME=/usr/local/jdk1.7.0_80export JRE_HOME=/usr/local/jdk1.7.0_80/jreexport CLASSPATH=.: ...

  6. Busybox shell脚本修改密码

    /****************************************************************************** * Busybox shell脚本修改密 ...

  7. dedecms列表页文章有图调用缩略图 无图留空或自定义图片的方法!

    默认情况下,织梦的文章列表页会调用出当前栏目下的文章列表,并且调用出每个文章的缩略图:如果文章本身就有图,会调用出一张小图,如果没有,则会显示默认的织梦图片.这种处理方式有时候比较影响美观,其实可以修 ...

  8. Find The Multiple(DFS)

    Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal repr ...

  9. 基于spring及zookeeper的dubbo工程搭建

    一.生产者搭建 新建一个maven工程,勾选Create a simple project Packaging方式选择jar包的方式. 修改pom.xml文件: <project xmlns=& ...

  10. Zabbix通过SNMPv2监控DELL服务器的硬件信息

    (一)zabbix监控DELL服务器 (1)简述:监控DELL服务器硬件一般有两种途径:1.操作系统上安装OMSA,编写脚本调用omreport命令进行监控(需要在操作系统上安装比较麻烦):2.使用i ...