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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • asp.net mvc 下拉框级联

    asp.net mvc 下拉框级联给自己需要级联的控制器添加要级联的下拉框获取#region//获取宿舍楼[HttpPost]publicActionResultDrom(stringid){objectobj=getDrom(id);returnJson(obj);}//获取宿舍楼publicList<SelectList.

    2022年7月22日
    6
  • vue-cli构建vue项目

    vue-cli构建vue项目

    2022年3月12日
    64
  • MATLAB中神经网络工具箱的使用「建议收藏」

    MATLAB中神经网络工具箱的使用「建议收藏」今夕何夕兮,前些天把玩了一下MATLAB中神经网络工具箱的使用,忽有“扪参历井仰胁息”之感。别的倒是没什么,只是神经网络的数据组织结构有些“怪异”,要是不小心就会导致工具箱报错。以下便是神经网络工具箱的正确打开姿势,谨供诸君参考:1.打开MATLAB,在命令行输入nntool,将出现如下界面:图1神经网络工具箱主界面其中最主要的分为6个部分:第1部分中显示的是系统的输…

    2022年6月20日
    120
  • 永久短网址生成 可以永久使用的短链接推荐

    永久短网址生成 可以永久使用的短链接推荐一、使用场景微博、短信、微信在推送信息的时候都有字符的数量限制,如果分享一个长网址,很容易就超出限制,发不出去。短网址服务可以把一个长网址变成短网址,方便在社交网络上传播。二、需求微信中链接过长容易被系统屏蔽,导致推送信息他人无法看到,或者是整个信息被收起来!短信、微博中字符数超级严格一旦超过了规定的字符数。就会导致信息发送失败!综上几个现在最长的场景,很显然,要尽可能的短…

    2022年5月31日
    251
  • 自动编码器重建图像及Python实现

    自动编码器重建图像及Python实现自动编码器简介自动编码器(一下简称AE)属于生成模型的一种,目前主流的生成模型有AE及其变种和生成对抗网络(GANs)及其变种。随着深度学习的出现,AE可以通过网络层堆叠形成深度自动编码器来实现数据降维。通过编码过程减少隐藏层中的单元数量,可以以分层的方式实现降维,在更深的隐藏层中获得更高级的特征,从而在解码过程中更好的重建数据。自动编码器原理自动编码器是通过无监督学习训练的神经网络,实际上…

    2022年5月18日
    53
  • 固态硬盘数据丢失能恢复吗?含泪分享:固态硬盘数据恢复方法

    固态硬盘数据丢失能恢复吗?含泪分享:固态硬盘数据恢复方法固态硬盘数据丢失能恢复吗?有些时候又是数据无缘无故丢失导致我们一头雾水的同时又手足无措。其实不论是固态硬盘,还是什么其他电子设备,数据丢失也是可以恢复的。固态硬盘的话,除非芯片被损坏或烧毁。那么点进来看看恢复的方法吧!…

    2022年9月20日
    0

发表回复

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

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