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

    public int onStartCommand(Intent intent, int flags, int startId) {

        Thread thread = new Thread(){
@Override
public void run() { /**
* 耗时的代码在子线程里面写
*/ }
};
thread.start(); return super.onStartCommand(intent, flags, startId);
}

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

 public void run() {

                /**
* 耗时的代码在子线程里面写
*/
stopSelf(); }

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <Button
android:id="@+id/bt_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/> </LinearLayout>

intentservice.xml

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

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

然后是服务类

package com.example.mydemo.intentservice;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast; /**
***************************************************************
*
* @版权 LinFeng
*
* @作者 LinFeng
*
* @版本 1.0
*
* @创建日期 2016-6-10
*
* @功能描述
*****************************************************************
*/ /**
* 注意,继承的是 IntentService而不是Service哦,还有,既然是服务,那么就必须在清单文件里面注册
*/
public class MyIntentService extends IntentService { @SuppressLint("HandlerLeak")
Handler handler = new Handler(){ @Override
public void handleMessage(Message msg) {
Toast.makeText(MyIntentService.this, "IntetnService Running", Toast.LENGTH_SHORT)
.show();
super.handleMessage(msg); }
}; /**
* 使用Eclipse如果没有添加这个无参构造函数的话会报一个运行时错误: java.lang.InstantiationException
*/
public MyIntentService() {
/**
* 这里只需要传入一个字符串就可以了
*/
super("MyIntentService"); } /**
* 必须实现的抽象方法,我们的业务逻辑就是在这个方法里面去实现的 在这个方法里实现业务逻辑,我们就不用去关心ANR的问题
*/
@Override
protected void onHandleIntent(Intent intent) { /**
* 因为这个方法是在子线程里面处理的,所以这里我们不能直接在子线程里面弹Toast
* 我们这里使用handler来帮助我们处理Toast
*/
handler.sendEmptyMessage(0);
} /**
* 为了验证onHandleIntent执行后,服务会不会自动销毁,我们在这里重写onDestroy方法
* 如果会自动销毁,那么在"IntetnService Running"出现后,应该会出现"IntetnService Stop"
*/
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "IntetnService Stop", Toast.LENGTH_SHORT).show();
} }

MyIntentService

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

package com.example.mydemo.intentservice;

import com.example.mydemo.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; /**
***************************************************************
*
* @版权 LinFeng
*
* @作者 LinFeng
*
* @版本 1.0
*
* @创建日期 2016-6-10
*
* @功能描述
*****************************************************************
*/
public class IntentServiceActivity extends Activity{ private Button btButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intentservice); btButton = (Button) findViewById(R.id.bt_start);
btButton.setText("Start IntentService"); btButton.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
Intent intent = new Intent(IntentServiceActivity.this,MyIntentService.class);
startService(intent);
}
});
} }

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. CSS基础(float属性与清除浮动)

    3.8 这是CSS里比较重要的属性:浮动,这个属性会在以后经常用到,算是一个重点吧 浮动 语法:float:left  |  right  |  none 特点: 浮动的元素不占位置,脱离了标准文档流 ...

  2. 删除OSX中第三方的「偏好设置」程序(.prefPane)

    打开Finder,按Command+Shift+G,输入 /Library/PreferencePanes ~/Library/PreferencePanes 前一个是全局的配置项目录,第二个是当前用 ...

  3. ES6 类(Class)基本用法和静态属性+方法详解

    原文地址:http://blog.csdn.net/pcaxb/article/details/53759637 ES6 类(Class)基本用法和静态属性+方法详解 JavaScript语言的传统方 ...

  4. ubuntu设置开机启动命令行模式

    1.命令: sudo gedit /etc/default/grub 找到这一行 GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" (ubuntu ...

  5. hadoop_异常_02_ExitCodeException exitCode=1: chmod: changing permissions of `/ray/hadoop/dfs/data': Operation not permitted

    一.异常现象 启动hadoop时,datanode启动失败,出现如下异常: 2018-03-23 14:39:09,962 WARN org.apache.hadoop.hdfs.server.dat ...

  6. LeetCode OJ:Lowest Common Ancestor of a Binary Search Tree(最浅的公共祖先)

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  7. java学习笔记 --- 网络编程(套接字)

    1.Socket通信原理 Socket套接字概述: 网络上具有唯一标识的IP地址和端口号组合在一起才能构成唯一能识别的标识符套接字. 通信的两端都有Socket. 网络通信其实就是Socket间的通信 ...

  8. 超简单tensorflow入门优化程序&&tensorboard可视化

    程序1 任务描述: x = 3.0, y = 100.0, 运算公式 x×W+b = y,求 W和b的最优解. 使用tensorflow编程实现: #-*- coding: utf-8 -*-) im ...

  9. itunesconnect如何提交被决绝过了的相同版本号

    遇到一次审核被拒,打算再次提交时,不想改变版本号,可以在xcode里把build版本号后面几个.1,比如version上次被拒时是1.1.3,build也是1.1.3,这次送审时version不变,b ...

  10. HihoCoder1182 欧拉路(Fleury算法)

    描述 小Hi和小Ho破解了一道又一道难题,终于来到了最后一关.只要打开眼前的宝箱就可以通关这个游戏了. 宝箱被一种奇怪的机关锁住: 这个机关是一个圆环,一共有2^N个区域,每个区域都可以改变颜色,在黑 ...