intentservice使用(Intention)

IntentService,更好用的Service说起IntentService就需要先了解一下Service。Service是长期运行在后台的应用程序组件。Service不是一个单独的进程,它和应用程序在同一个进程中,Service也不是一个线程,它和线程没有任何关系,所以它不能直接处理耗时操作。如果直接把耗时操作放在Service的onStartCommand()中,…

大家好,又见面了,我是你们的朋友全栈君。

IntentService浅析

说起IntentService就需要先了解一下Service

Service 是长期运行在后台的应用程序组件。

Service 不是一个单独的进程,它和应用程序在同一个进程中,Service 也不是一个线程,它和线程没有任何关系,所以它不能直接处理耗时操作。如果直接把耗时操作放在 Service 的 onStartCommand() 中,很容易引起 ANR(ActivityManagerService.java中定义了超时时间,前台service超过20S,后台Service超过200S无响应就会ANR) 。如果有耗时操作就必须开启一个单独的线程来处理。

既然Service不能直接执行耗时操作,那么在Service开启子线程执行耗时操作不就好了。当然,这么想完全没毛病,在Service中执行耗时操作也只能这么干。如:

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);
}

正如前面说到,Service是长期运行在后台的应用程序组件,那么Service一旦启动就会一直运行下去,必须人为调用stopService()或者stopSelf()方法才能让服务停止下来。如果耗时操作只想执行一次,那么必须在执行耗时操作的子线程执行完后就结束Service自身。如:

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

或者在代码里的某个地方调用stopService()或者stopSelf()方法。

这么做是否很麻烦呢?如果忘记在Service开始子线程呢?如果忘记结束Service呢?

所以引入了今天的话题:IntentService

IntentService 是继承于 Service 并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作,启动 IntentService 的方式和启动传统 Service 一样,同时,当任务执行完后,IntentService 会自动停止,而不需要我们去手动控制。另外,可以启动 IntentService 多次,而每一个耗时操作会以工作队列的方式在IntentService 的 onHandleIntent 回调方法中执行,并且,每次只会执行一个工作线程,执行完第一个再执行第二个,以此类推。

而且,所有请求都在一个单线程中,不会阻塞应用程序的主线程(UI Thread),同一时间只处理一个请求。 那么,用 IntentService 有什么好处呢?首先,我们省去了在 Service 中手动开线程的麻烦,第二,当操作完成时,我们不用手动停止 Service。

IntentService源码分析

package android.app;

import android.annotation.WorkerThread;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

/**
 * IntentService is a base class for {@link Service}s that handle asynchronous
 * requests (expressed as {@link Intent}s) on demand.  Clients send requests
 * through {@link android.content.Context#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.
 *
 * <p>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 {@link #onHandleIntent(Intent)}.  IntentService
 * will receive the Intents, launch a worker thread, and stop the service as
 * appropriate.
 *
 * <p>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.
 *
 * <div class="special reference">
 * <h3>Developer Guides</h3>
 * <p>For a detailed discussion about how to create services, read the
 * <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> developer guide.</p>
 * </div>
 *
 * @see android.os.AsyncTask
 */
public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

    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);
        }
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public IntentService(String name) {
        super();
        mName = name;
    }

    /**
     * Sets intent redelivery preferences.  Usually called from the constructor
     * with your preferred semantics.
     *
     * <p>If enabled is true,
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_REDELIVER_INTENT}, so if this process dies before
     * {@link #onHandleIntent(Intent)} returns, the process will be restarted
     * and the intent redelivered.  If multiple Intents have been sent, only
     * the most recent one is guaranteed to be redelivered.
     *
     * <p>If enabled is false (the default),
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
     * dies along with it.
     */
    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    @Override
    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.

        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

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

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

    /**
     * You should not override this method for your IntentService. Instead,
     * override {@link #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * @see android.app.Service#onStartCommand
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }

    /**
     * Unless you provide binding for your service, you don't need to implement this
     * method, because the default implementation returns null. 
     * @see android.app.Service#onBind
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * This method is invoked on the worker thread with a request to process.
     * Only one Intent is processed at a time, but the processing happens on a
     * worker thread that runs independently from other application logic.
     * So, if this code takes a long time, it will hold up other requests to
     * the same IntentService, but it will not hold up anything else.
     * When all requests have been handled, the IntentService stops itself,
     * so you should not call {@link #stopSelf}.
     *
     * @param intent The value passed to {@link
     *               android.content.Context#startService(Intent)}.
     */
    @WorkerThread
    protected abstract void onHandleIntent(Intent intent);
}

Service有startService()bindService()两种启动方式,那么IntentService是否也有呢?

 	/**
     * Unless you provide binding for your service, you don't need to implement this
     * method, because the default implementation returns null. 
     * @see android.app.Service#onBind
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

IntentService 源码中的 onBind() 默认返回 null;不适合 bindService() 启动服务,如果你执意要 bindService() 来启动 IntentService,可能因为你想通过 Binder 或 Messenger 使得 IntentService 和 Activity 可以通信,这样那么 onHandleIntent() 不会被回调,相当于在你使用 Service 而不是 IntentService。因此,并不建议通过 bindService() 启动 IntentService,而是通过startService()来启动IntentService。

为什么多次启动 IntentService 会顺序执行事件,停止服务后,后续的事件得不到执行?

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

@Override
public void onDestroy() {
    mServiceLooper.quit();
}

IntentService 中使用的 Handler、Looper、MessageQueue 机制把消息发送到线程中去执行的,所以多次启动 IntentService 不会重新创建新的服务和新的线程,只是把消息加入消息队列中等待执行,而如果服务停止,会清除消息队列中的消息,后续的事件得不到执行。

使用方法:

1、创建一个类并继承IntentService,重写onHandleIntent(),构造函数super("线程名");

2、在AndroidManifest.xml里注册,同Service;

3、通过startService()启动。

package com.eebbk.synchinese.widgetutil;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;

/**
 * 刷新桌面挂件
 * Created by zhangshao on 2018/2/28.
 */
public class WidgetUpdateService extends IntentService {

	public WidgetUpdateService() {
		super("WidgetUpdateService");
	}

	@Override
	protected void onHandleIntent(@Nullable Intent intent) {
		synchronized (this) {
			FastOpenBookUtil.refreshLearnBookWidgetBroadCast(this);
		}
	}
}

附:

ActivityManagerService.java中ANR的超时时间定义:

1、Broadcast超时时间为10秒:

// How long we allow a receiver to run before giving up on it.
static final int BROADCAST_FG_TIMEOUT = 10*1000;
static final int BROADCAST_BG_TIMEOUT = 60*1000;

2、按键无响应的超时时间为5秒

// How long we wait until we timeout on key dispatching.
static final int KEY_DISPATCHING_TIMEOUT = 5*1000;

3、Service的ANR在ActiveServices中定义:

前台service无响应的超时时间为20秒,后台service为200秒

// How long we wait for a service to finish executing.
static final int SERVICE_TIMEOUT = 20*1000;

// How long we wait for a service to finish executing.
static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/125861.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 安装office2016时弹出microsoft setup bootstrapper已停止工作的解决办法

    安装office2016时弹出microsoft setup bootstrapper已停止工作的解决办法安装office2016时安装进度条走到最后又回滚,弹出microsoftsetupbootstrapper已停止工作,最后“安装出错”经过了1天的试尽了各种控制面板卸载、文件夹删除、office注册表删除等方法,最后用了以下方法才终于解决。希望没试过我这个方法的朋友们先试下这个方法。(⊙o⊙)…确认启动WindowsEventLog这个服务项。Windows系统的服务打开方…

    2022年7月20日
    40
  • 1. Git安装与配置

    1. Git安装与配置本文介绍Windows下的Git安装与配置

    2022年6月1日
    31
  • eplan激活码【2021最新】

    (eplan激活码)本文适用于JetBrains家族所有ide,包括IntelliJidea,phpstorm,webstorm,pycharm,datagrip等。IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html…

    2022年3月22日
    298
  • autoconf产生Makefile流程

    autoconf产生Makefile流程生成Makefile的流程。参考http://www.ibm.com/developerworks/cn/linux/l-makefile/首先进入project目录,在该目录下运行一系列命令,创建和修改几个文件,就可以生成符合该平台的Makefile文件,操作过程如下:1)运行autoscan命令2)将configure.scan文件重命名为configure.

    2022年6月3日
    36
  • makefile 编译参数_gcc使用说明

    makefile 编译参数_gcc使用说明gcc编译源文件共有4个过程,预处理、编译、汇编、链接。预处理:命令:gcc-Etest.c-otest.i(-o后面指定生成文件的命名)过程:展开宏定义(#define),处理编译条件指令(#if#ifndef等),插入引用的头文件(#include),删除注释,添加行号和文件标识。结果:生成.i文件,一般的文本编辑器都能打开编译:命令:gcc-Ste…

    2022年10月13日
    1
  • RuntimeException和非RuntimeException的区别「建议收藏」

    RuntimeException和非RuntimeException的区别「建议收藏」通俗一点:   Error:系统级别的错误,如栈溢出内存溢出之类 ,此类错误一般情概况保证程序能安全退出即可   Exception:分为RuntimeException 和 非RuntimeException                                                                           …

    2022年7月18日
    16

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号