首页 > 其他分享 >Android IntentService使用

Android IntentService使用

时间:2023-06-01 10:04:51浏览次数:27  
标签:onHandleIntent 15 03 3186 IntentService 使用 Android MyIntentService


概述


演示使用Android 中IntentService的方法。IntentService一般情况下,用于后台处理一些耗资源的任务。本例子有演示使用这个IntentService类的代码,并可运行。


详细

一、准备工作


开发环境:

jdk1.8

Eclipse Luna Service Release 1 (4.4.1)

运行环境:

华为荣耀6(Android4.4)、华为p9(Android7.0)

实现功能:

Android IntentService的使用

二、简介

IntentService概括

IntentService is a base class for Service that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. 
This “work queue processor” pattern is commonly used to offload tasks from an application’s main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate. 
All requests are handled on a single worker thread – they may take as long as necessary (and will not block the application’s main loop), but only one request will be processed at a time.

IntentService是Service的子类,根据需要处理异步请求(以intent表示)。客户端通过调用startService(Intent) 发送请求,该Service根据需要启动,使用工作线程处理依次每个Intent,并在停止工作时停止自身。 
这种“工作队列处理器”模式通常用于从应用程序的主线程中卸载任务。 IntentService类的存在是为了简化这种模式。 要使用它,扩展IntentService并实现onHandleIntent(Intent)。 IntentService将收到Intents,启动一个工作线程,并根据需要停止该服务。 
所有请求都在单个工作线程处理 - 它们可能需要很长的时间(并且不会阻止应用程序的主循环),但是一次只会处理一个请求

三、程序实现

工程截图:

Android IntentService使用_构造方法

在IntentService中处理下载请求(模拟),并将进度更新到Ui。 
MyIntentService.Java代码如下:

public class MyIntentService extends IntentService {
    private final static String TAG = "MyIntentService";
    
    public static final String ACTION_DOWN_IMG = "down.image";
    public static final String ACTION_DOWN_VID = "down.vid";

    public static final String ACTION_DOWN_PROGRESS = "com.zpengyong.down.progress";
    public static final String ACTION_SERVICE_STATE = "com.zpengyong.service.state";
    
    public static final String PROGRESS = "progress";
    public static final String SERVICE_STATE = "service_state";

    //构造方法
    public MyIntentService() {
        super("MyIntentService");
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        sendServiceState("onCreate");
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "");
    }
    
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(TAG, "onHandleIntent thread:"+Thread.currentThread());
        String action = intent.getAction();
        if(action.equals(ACTION_DOWN_IMG)){
            for(int i = 0; i < 100; i++){
                try{ //模拟耗时操作
                    Thread.sleep(50);
                }catch (Exception e) {
                }
                sendProgress(i);
            }
        }else if(action.equals(ACTION_DOWN_VID)){
            for(int i = 0; i < 100; i++){
                try{ //模拟耗时操作
                    Thread.sleep(70);
                }catch (Exception e) {
                }
                sendProgress(i);
            }
        }
        Log.i(TAG, "onHandleIntent end");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        sendServiceState("onDestroy");
    }
    //发送Service的状态
    private void sendServiceState(String state){
        Intent intent = new Intent();
        intent.setAction(ACTION_SERVICE_STATE);
        intent.putExtra(SERVICE_STATE, state);
        sendBroadcast(intent);
    }
    
    //发送进度
    private void sendProgress(int progress){
        Intent intent = new Intent();
        intent.setAction(ACTION_DOWN_PROGRESS);
        intent.putExtra(PROGRESS, progress);
        sendBroadcast(intent);
    }
}

使用IntentService的方法:

  1. 继承IntentService。
  2. 实现不带参数的构造方法,并且调用父类IntentService的构造方法。
  3. 实现onHandleIntent方法。

在onHandleIntent方法中可以根据intent来区分任务,这里有两个任务,一个是下载图片、一个是下载视频(模拟耗时操作)。

四、运行效果

项目下载后,导入eclipse后,右键项目:Run as -》Android Application

然后有以下效果:

1 只点击“启动任务一”。 

Android IntentService使用_子线程_02

 

打印:

07-15 03:07:24.589: I/MyIntentService(3186): onCreate07-15 03:07:24.593: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:07:30.918: I/MyIntentService(3186): onHandleIntent end
07-15 03:07:31.017: I/MyIntentService(3186): onDestroy


IntentService启动后再onHandleIntent方法中执行任务(该方法工作在子线程中),任务执行完后,IntentService销毁。

2 点击“启动任务一”,任务未完成时点击“停止Service”。 

Android IntentService使用_Android_03

 

log

07-15 03:08:08.477: I/MyIntentService(3186): onCreate07-15 03:08:08.478: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]07-15 03:08:12.203: I/MyIntentService(3186): onDestroy
07-15 03:08:14.253: I/MyIntentService(3186): onHandleIntent end


IntentService中线程执行任务时,stopService会让IntentService销毁,但是任务继续执行,直到执行完成线程退出。

3 点击“启动任务一”,任务完成后点击“启动任务二”。 

Android IntentService使用_子线程_04

 

log信息:

07-15 03:11:42.366: I/MyIntentService(3186): onCreate07-15 03:11:42.367: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]07-15 03:11:48.285: I/MyIntentService(3186): onHandleIntent end07-15 03:11:48.289: I/MyIntentService(3186): onDestroy
07-15 03:11:50.174: I/MyIntentService(3186): onCreate
07-15 03:11:50.205: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:11:58.446: I/MyIntentService(3186): onHandleIntent end
07-15 03:11:58.510: I/MyIntentService(3186): onDestroy


由上可知,任务执行完成后,线程退出循环,Service销毁。重新开启任务则重新创建Service,执行任务。

4 点击“启动任务一”,任务完成前点击“启动任务二”。 

Android IntentService使用_构造方法_05

 

log信息

07-15 03:16:46.998: I/MyIntentService(3186): onCreate07-15 03:16:46.998: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]07-15 03:16:52.980: I/MyIntentService(3186): onHandleIntent end07-15 03:16:52.980: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]07-15 03:17:01.048: I/MyIntentService(3186): onHandleIntent end
07-15 03:17:01.053: I/MyIntentService(3186): onDestroy


正常startService启动两个任务,第一个未完成前,将第二个任务放到队列中,等待第一个完成后执行第二个任务,第二个任务完成后,Service自动销毁。

5 点击“启动任务一”,任务完成前点击“停止Service”,然后再点击“启动任务二”。 

Android IntentService使用_构造方法_06

 

log信息 

Android IntentService使用_ide_07

 

第一个任务尚未结束时stopservice,IntentService销毁,其线程继续运行(tid 3691)。此时重新startService会开启IntentService,其会重新创建一个线程运行任务(tid 3692)。两个任务在两个线程中运行,所以其执行完的先后顺序不确定。

五、补充说明:IntentService源码解析

路径:frameworks/base/core/java/android/app/IntentService.java 
先看下IntentService的构造方法和onCreate()。

public abstract class IntentService extends Service {
    //Creates an IntentService.Invoked by your subclass's constructor.
    public IntentService(String name) {
            super();
        mName = name;
    }
     @Override
    public void onCreate() {
             super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }
    。。。。
}

IntentService 是继承Service的一个抽象类,所以需要继承IntentService 并必须实现其抽象方法onHandleIntent。 
继承IntentService需要实现一个空的构造器,并且调用IntentService的构造器。 
在onCreate()方法中创建了一个HandlerThread,并允许该线程。HandlerThread 不太懂的可以参考我的上一篇文章Android HandlerThread详解 。 
获取子线程中的Looper实例,然后创建与子线程绑定的Handler对象。


接着看IntentService的onStart()。

public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
     msg.arg1 = startId;
     msg.obj = intent;
     mServiceHandler.sendMessage(msg);
}

在onStart方法中,创建Message对象,并将“消息”通过mServiceHandler发送到子线程中的消息队列中。 
我们知道这些消息处理还是会分发到Handler中。接着看mServiceHandler

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
             super(looper);
     }
     @Override
     public void handleMessage(Message msg) {
             onHandleIntent((Intent)msg.obj);
         stopSelf(msg.arg1);
    }
}

消息会在handlerMessage中处理,该方法中调用了onHandleIntent,所以我们需要实现onHandleIntent,在该方法中做我们要做的任务。而消息处理完成后,调用stopSelf将自身Service销毁。这里可能会有疑问,既然一个任务执行完成后就会执行stopSelf,那多个任务是怎么处理的呢?这里stopSelf(msg.arg1),会先看队列中是否有消息待处理,如果有则继续处理后面的消息,没有才会将Service销毁。 

接着看IntentService的onDestroy方法。

@Overridepublic void onDestroy() {
    mServiceLooper.quit();
}

在IntentService的onDestroy方法中会调用looper的quit方法,将子线程的消息循环停止,等待任务完成后结束子线程。


六、总结

IntentService是一个比较便捷的类,省了我们在创建Thread,但是并不能适合所有的情况,它会创建一个线程,多个任务按顺序执行,并且执行过程中不能够取消该任务。所以还是需要根据情况进行使用。


注:本文著作权归作者,由demo大师宣传,拒绝转载,转载需要作者授权



标签:onHandleIntent,15,03,3186,IntentService,使用,Android,MyIntentService
From: https://blog.51cto.com/u_7583030/6392455

相关文章

  • AsyncTask 异步任务基本使用-下载视频
    概述android提供了一个异步任务类AsyncTask,使创建异步任务、更新UI变得更加简单,不再需要编写任务线程和Handler实例即可完成相同的任务。本例子将演示并实现,使用AsyncTask来下载视频。详细一、准备工作开发环境:jdk1.8EclipseLunaServiceRelease1(4.4.1)运行环......
  • 使用SpringMVC搭建第一个项目
    概述使用SpringMVC搭建第一个项目,入门教程,分享给大家。详细一、概述1、什么是SpringMVC?SpringMVC属于SpringFrameWork的后续产品,已经融合在SpringWebFlow里面。Spring框架提供了构建Web应用程序的全功能MVC模块。使用Spring可插入的MVC架构,从而在使用Sp......
  • JavaWeb——Tomcat服务器的安装与使用
    今天阿Q带大家了解服务器的概念以及tomcat服务器的安装和使用方法,废话不多说直接上干货。Web开发中的常见概念(1)B/S系统和C/S系统Brower/Server:浏览器、服务器系统-----网站Client/Server:客户端、服务器系统-----QQ、大型游戏(2)web应用服务器供向外部发布web资源的服务器软件......
  • Android基于TCP的局域网聊天通信
    概述在同一局域网内,两台设备通过TCP进行通信聊天。详细一、准备工作开发环境jdk1.8 EclipseLunaServiceRelease1(4.4.1)运行环境:华为荣耀6(Android4.4)、华为p9(Android7.0)实现功能:同一局域网下,两台设备进行tcp通信聊天。二、程序实现工程截图:2、实现思路Androi......
  • 基于FFmpeg的音频编码(PCM数据编码成AAC android)
    概述在Android上实现录音,并利用FFmpeg将PCM数据编码成AAC。详细之前做的一个demo,Android录音获取pcm数据(音频原始数据),然后利用FFmpeg将PCM数据编码成AAC。一、准备工作开发环境jdk1.8 EclipseLunaServiceRelease1(4.4.1)运行环境:华为荣耀6(Android4.4)、华为......
  • 如何使用CheckMenuItem添加可选菜单项
    如何使用CheckMenuItem添加可选菜单项CheckMenuItem也是一种菜单项目,类似CheckBox,拥有可选状态。CheckMenuItem可以添加到菜单中。效果展示示例代码importjavafx.application.Application;importjavafx.scene.Scene;importjavafx.scene.control.CheckMenuItem;imp......
  • Eclipse的安装与使用
    相信大家在用记事本编译运行java程序的同时肯定心里有不少怨言吧,要是用这种工具编译一个复杂点的程序简直就有想死的心了,更不用说什么大的网站项目了。接下来阿Q就带领大家了解一个全新的编译工具Eclipse。Eclipse的安装首先进入eclipse的官方网站http://eclipse.org/(org是非盈利......
  • 如何使用RadioMenuItem添加单选菜单项
    如何使用RadioMenuItem添加单选菜单项几个RadioMenuItem可以组成一个组合,组合中只能有一个菜单条目被选择。效果展示示例代码importjavafx.application.Application;importjavafx.scene.Scene;importjavafx.scene.control.Menu;importjavafx.scene.control.MenuBar;......
  • layui 基础使用一
    table中单元格可点击,数据样式渲染:table.render的配置项cols所在列配置如下:{field:'name',title:'姓名',width:120,templet:function(d){varnameDom='<aclass="table-inner-handle">'+d.name+'</a>&#......
  • 如何使用Next.js创建全栈应用程序
    Next.js乍一看似乎令人生畏,因为有这么多新概念需要掌握。但别担心——在这个循序渐进的教程中,我将为您提供使用Next.js创建您的第一个现代全栈应用程序所需的所有基本信息。在本教程中,我将带您了解Next.js的基础知识,并指导您创建您的第一个全栈应用程序。在本教程结束时,您将......