Android学习(2.5)—— Service 与 IntentService

快速了解Service 与IntentService Service IntentService   我们都知道安卓UI线程(Activity)里面禁止进行耗时操作,否则将会抛出异常。因此我们如需执行长时间耗时任务(比如上传、下载等任务)的话,还需的单独开一个任务线程来执行,这里我们可以选择IntentService或Service来在后台执行我们的耗时任务。如果任务处理结果要显示到UI界面上的话,那么选择IntentService比较合适。如果... 阅读详情

Service 与 IntentService

面试的时候总是能看到有人问这两个有啥区别,也不知道有啥问的,IntentService是Service的子类啊,是Service功能的封装啊,本质上就没啥可比性,等级都不同,为啥要问区别呢?

Service

我有一篇博客,嘻嘻嘻,我就不多说了。

IntentService

IntentService是一个方便我们处理业务流程的类,它也是一个Service,但是比Service更智能。

由于service 的回调方法都是跑在主线程中,所以Service并不是新开一条线程而是运行在UI线程中,那么如果你在Service的onStartCommond方法中执行了耗时的操作依旧是会造成ANR的,所以如果你要处理耗时操作,那么就需要重新起一条线程,或者就是使用IntentService(其实IntentService就是起了一条线程在跑,并且他所有的请求都是在一个新线程中,不会阻塞UI线程)

IntentService的源码

/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.app;

import android.annotation.WorkerThread;
import android.annotation.Nullable;
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/components/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(@Nullable 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(@Nullable 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
    @Nullable
    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)}.
     *               This may be null if the service is being restarted after
     *               its process has gone away; see
     *               {@link android.app.Service#onStartCommand}
     *               for details.
     */
    @WorkerThread
    protected abstract void onHandleIntent(@Nullable Intent intent);
}


注意

  • IntentService不会同事处理所有的请求,而是通过非UI线程逐一处理,如果不要求服务同时处理多个请求,可以考虑使用IntentService。

  • IntentService中onBind()方法默认返回null,这说明启动IntetService的方式最好是用startService方法,在服务执行完毕后需要调用stopSelf()才好

  • IntentService在内部使用与Handler配合使用

    这个是从一个以前看过的博客上看到的

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

public int onStartCommand(Intent intent, int flags, int startId) {
    onStart(intent, startId);
    return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}

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

从源代码里面可以看见,在执行完毕onHandleIntent方法后,会执行stopSelf来关闭本身,stopSelf(int startID)方法作用是在其参数startId跟最后启动该service时生成的id相等时才会执行停止服务,当有多个请求时候,如果发现当前请求的startId不是最后一个请求的id,那么不会停止服务,所以只有当最后一个请求执行完毕后,才会停止服务。

android 中的服务Service intentService例子 NULL 博文链接:https://zhanglimijavaeye.iteye.com/blog/1881599 立即下载

相关推荐

深入剖析Android系统中Service和IntentService的区别

主要介绍了Android系统中Service和IntentService的区别,与普通的服务相比,IntentService可以开启单独的线程来处理intent请求,需要的朋友可以参考下

服务Service与IntentService

是能够在后台长时间执行操作并且不是供用户界面的应用程序组件。Senice可以与其他组件进行交互,一般由Activity启动,但是并不依赖于Activity。Service通常被称为“后台服务”,其中“后台”一词是相对于前台而言的,。除此之外,Service还具有较长时间运行特性,它的应用场景主要有两个,分别是后台运行和跨进程访问。1.后台运行:Senvice可以在后台长时间进行操作而不用提供界面信息,只有当系统必须要回收内存资源时,才会被毁,否则Service会一直在后台运行。

m0_57150356的博客 886

手把手教你用Multisim 14.2仿真一个4.4V的LDO电路(附完整仿真文件)

本文详细介绍了如何使用Multisim 14.2仿真一个4.4V的LDO电路,从环境配置、核心参数解析到电路搭建和仿真调试。通过分压电阻精确计算和瞬态响应测试,帮助读者掌握LDO电路的设计与验证技巧,并附有完整仿真文件供参考。

weixin_28738397的博客 275

Service与IntentService

intentService继承Service,在onCreate时会创建一个线程,在onStart时可以向线程发送handler发送消息。可以执行耗时操作,Service不能执行耗时操作 Service是什么? Service是Android四大组件之一,Service是长期运行在后台的应用程序组件。 Service不是进程,也不是线程,它和应用程序在同一个进程中,它更像是一个没有UI的Activity Service运行在主线程中,不能做耗时操作 ...

杰锅锅dev 731

ESXI 7 :创建统信V20_1050d服务器系统虚拟机

记录一下在 X86 架构创建统信V20_1050d 虚拟机遇到的问题。已遇到的问题有①:常规服务器环境下网络连接失败重点:按照桌面版本,有问题处理简单。

guyuelin123的博客 1969

基于STM32的超声波流量计设计

本项目基于STM32微控制器设计了一种超声波流量计,采用时间差法测量液体或气体的流速,计算流量并通过显示屏实时显示,同时支持远程数据传输。本设计通过STM32微控制器实现了基于时间差法的超声波流量计,集成了超声波信号采集、流量计算、状态显示和远程通信功能。本系统需要实现超声波信号的实时采集与处理,计算流速和流量,并将数据通过OLED显示和无线模块上传。系统需具备高精度的时间测量能力和良好的抗干扰能力。通过计算超声波在顺流和逆流方向上的传播时间差,结合管道直径与流体特性,计算流速并进一步计算流量。

stm32d1219的博客 2351

Service 与 IntentService

一、概述 Service为Android四大组件之一,与Activity不同的是,Service没有图形用户界面,是运行不可见的,是长生命周期的。而Activity是有图形界面,有固定生命周期的,只能在生命周期内启动,停止,重新创建。 启动一个Service或以通过其它组件,比如:Activity,Broadcast Receiver,ContentProvider或其它的Service来启动

死磕到底 729

ANSYS_APDL实战入门——从零开始掌握模态分析

本文为ANSYS APDL模态分析实战入门指南,通过一个悬臂梁案例,手把手教你从零开始掌握APDL命令流。内容涵盖从模型创建、材料定义、网格划分到边界条件设置、求解及后处理结果查看的全流程,帮助工程师快速上手结构动力学分析,避免共振风险。

egg99的博客 1132

IntentService 与 Service的区别

IntentService 与 Service的区别:(service(不是单独进程和应用程序同进程)intentService(是一个处理异步请求类,专处理耗时任务)) Service 是长期运行在后台的应用程序组件。 Service 不是一个单独的进程,它和应用程序在同一个进程中, Service 也不是一个线程,它和线程没有任何关系,所以它不能直接处理耗时操作。 如果直接把耗时操作放在 Service 的 onStartCommand() 中,很容易引起 ANR .如果有耗时操作就必须开启一.

zjxwon的博客 3273

避坑指南:C#调用CodeSoft打印标签时常见的5个错误及解决方法

本文总结了C#调用CodeSoft打印标签时常见的5个核心错误及解决方案,涵盖环境配置、模板加载、变量赋值、打印机切换和资源管理。重点解析了如何避免COM对象创建失败、模板路径错误、变量名不匹配、打印机切换异常及内存泄漏等问题,帮助开发者实现稳定高效的标签打印集成。

weixin_29215815的博客 232

如何用DeepSeek写年底工作总结?——从入门到精通的全流程指南

AI助手DeepSeek如何高效撰写工作总结 摘要:本文介绍如何利用DeepSeek智能AI助手高效完成工作总结写作。工作总结具有结构固定、语言规范、内容数据化三大特性,而DeepSeek的结构化生成、风格适配、数据整合和迭代优化四大核心能力与之完美匹配。文章提出"准备-搭架-填充-优化"四步工作法:1)精准输入岗位、时间范围等核心信息;2)先搭建逻辑清晰的提纲框架;3)分模块填充具体内容,突出数据与案例;4)通过风格润色和细节补充进行优化。通过合理运用多模态材料处理能力,DeepSee

通俗易懂学IT 291

Android:安卓学习笔记之Service 的简单理解和使用

Service 的简单理解和使用Service1、简介1.1、背景1.2、什么是Service?2、生命周期2.1、常用函数2.2、生命周期方法具体介绍3、分类4、使用4.1、本地Service4.2、可通信的服务Service4.3、前台Service4.4、IntentService4.4.1、Service和IntentService对比4.4.2、使用4.4.3、源码分析5、总结6、面试问题参考 Service 1、简介 1.1、背景 你一般在什么情况下会使用Service? 经验总结: Ser

JMW1407的博客 6665

【嘉立创EDA】从AD21导入pcb边界到嘉立创EDA专业版

有许多前期工程由AD进行完成,在后续update的过程中,由于开模等原因限制,部分pcb外型需要继续沿用,本文将此过程记录,以供有需要的读者参考。

l64481000的博客 4526

Service和IntentService的区别

Service和IntentService的区别 1. 首先IntentService是继承自Service; 2. Service不是一个单独的进程,它和应用程序在同一个进程中; 3. Service也不是一个线程,所以我们要避免在Service中进行耗时的操作; 4. IntentService使用队列的方式将请求的Intent加入队列,然后开启了一个Worker Thre

Android司机 5458

【ComfyUI】FluxKontext 身形调优与体态增强

AI身形调优与体态增强解决方案 该工作流通过Flux系列模型实现人物体态的智能化增强,主要特点包括: 采用UNet主体模型+双文本编码器+身形增强LoRA的架构组合 通过ReferenceLatent保持原始姿态的同时强化胸腰臀比例 完整工作流包含图像加载、文本编码、潜空间映射等8个核心节点 支持自动化的前后效果对比展示 应用优势: 保持人物自然姿态的前提下实现局部强化 支持通过Prompt精确控制增强方向 适用于摄影后期、角色美化等创作场景 输出效果稳定且风格统一 使用方

Mr数据杨 1304

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

android service 继承IntentService和Service

在manifest中声明一个service   跟activity以及其它组件一样,你必须在你的应用的manifest文件中声明所有的service们.   要声明你的service,添加一个元素作为元素的儿子.例如: ... ... 就像一个activity,一个service可以定义intent过滤器来使得其它组件使用明

xian00000的专栏 1157

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

android之Service(2)IntentService

IntentService是能够自动停止的Service,常用于处理一次性的异步操作(单独开一个工作线程),不存在ANR问题。

sywyg 7万+

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

IntentService详解

转载请注明链接:https://blog.csdn.net/feather_wch/article/details/82556153 详细介绍IntentService,并解析源码。看完本文你可以掌握问题汇总中所有问题的答案。做到精通IntentService IntentService 版本:2018/9/9-1(10:10) IntentService 问题汇总 I...

feather(猎羽) 6288

Android开发之Service和IntentService中显示Toast的区别

1. 表象 Service中可以正常显示Toast,IntentService中不能正常显示Toast,在2.3系统上,不显示toast,在4.3系统上,toast显示,但是不会消失。 2. 原因 Toast要求运行在UI主线程中。 Service运行在主线程中,因此Toast是正常的。 IntentService运行在独立的线程中,因此Toast不正常。

成信物联星的学习笔记 767

service与IntentService 区别

关系:   IntentService继承service 区别:   IntentService 是一个带有HandlerThread的线程的service,把任务执行完成以后IntentService自动销毁。   Service要手动 调用stopSelf()来销毁。   IntentService 运行在子线程中,Service运行在主线程中 作用:   In...

dgyibo2014的博客 200

Android笔记 IntentService与Service的区别

Service 在官方API(http://developer.android.com/reference/android/app/Service.htmlhttp://developer.android.com/reference/android/app/Service.html)的描述为A Service is an application component representing eit

小崔的博客 1万+

Android开发之Service与IntentService的区别与使用场景(源代码剖析)

因为最大部分的service不需要同时处理多个请求(处理多个请求是一个比较危险的多线程的场景),这样在在这种情况下呢,最好使用IntentService类如果你实现你的服务。   使用intentService与service有什么不同呢  (1)直接 创建一个默认的工作线程,该线程执行所有的intent传递给onStartCommand()区别于应用程序的主线程。  (2)直接创建一个工作

林泓成的专栏 1万+

Android自学之路——Service与IntentService

A)MainActivity部分的代码1 package com.example.cms.intentservice; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 impor...

agjhtyvm215883的博客 128

Service 和 IntentService的区别

Srevice不是在子线程,在Srevice中做耗时操作一样ANR,然后我们就会用到IntentService,IntentSrevice不但擅长做耗时操作,还有一个特点,用完即走; 在Srevice中做耗时轮询操作,使用Handler: public class MyService extends Service { public MyService() { } @Override publi...

awodefengduanwu的博客 138
上一篇: Android学习(二)——四大组件之Service
下一篇: Android学习(三)——四大组件之BroadcastReceiver
豪利丶王
博客等级 码龄11年 1粉丝 17原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值