Android Studio的代码笔记--IntentService学习

IntentService学习

IntentService

一个 HandlerThread工作线程,通过Handler实现把消息加入消息队列中等待执行,通过传递的intent在onHandleIntent中处理任务。(多次调用会按顺序执行事件,服务停止清除消息队列中的消息。)

适用:线程任务按顺序在后台执行,例如下载

不适用:多个数据同时请求

1、IntentService与Service的区别

从属性作用上来说

Service:依赖于应用程序的主线程(不是独立的进程 or 线程)。需要主动调用stopSelft()来结束服务

不建议在Service中编写耗时的逻辑和操作,否则会引起ANR;

IntentService:创建一个工作线程来处理多线程任务。在所有intent被处理完后,系统会自动关闭服务

2、IntentService与其他线程的区别

IntentService内部采用了HandlerThread实现,作用类似于后台线程;

与后台线程相比,IntentService是一种后台服务,优势是:优先级高(不容易被系统杀死),从而保证任务的执行。

对于后台线程,若进程中没有活动的四大组件,则该线程的优先级非常低,容易被系统杀死,无法保证任务的执行

常规用法

清单注册服务

java 复制代码
<service android:name=".SerialService">
            <intent-filter>
                <action android:name="android.service.newland.serial" />
            </intent-filter>
        </service>

服务内容

java 复制代码
package com.lxh.serialport;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
public class SerialService extends IntentService {
    private static final String TAG = "SerialService lxh";
    private static String ACTION_Serial = "android.service.serial";

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

    public static void startSS(Context context) {
        Intent intent = new Intent(context, SerialService.class);
        intent.setAction(ACTION_Serial);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (action.equals(ACTION_Serial)) {
//                mSerialInter = new modeSerialInter();
//                SerialManage.getInstance().init(mSerialInter);
//                SerialManage.getInstance().open();
            }
        }
    }
}

开启服务

java 复制代码
SerialService.startSS(this);

感谢互联网

适合阅读文章分享
Android IntentService详解

与君共勉!待续

欢迎指错,一起学习

相关推荐
程序员陆业聪4 小时前
从 OpenClaw 到 Android:Harness Engineering 是怎么让 Agent 变得可用的
android
daidaidaiyu5 小时前
一文学习 工作流开发 BPMN、 Flowable
java
SuniaWang6 小时前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题六:《Vue3 前端开发实战:打造企业级 RAG 问答界面》
java·前端·人工智能·spring boot·后端·spring·架构
sheji34166 小时前
【开题答辩全过程】以 基于springboot的扶贫系统为例,包含答辩的问题和答案
java·spring boot·后端
nap-joker6 小时前
【多模态解耦】DecAlign:用于解耦多模态表示学习的分层跨模态对齐
学习·多模态融合·最优传输·多模态表征学习·特征解耦·音频+图像+文本·原型引导
shuangrenlong6 小时前
gralde编译不过,编译问题
android studio
hnlgzb6 小时前
常见的Android Jetpack库会有哪些?这些库中又有哪些常用类的?
android·android jetpack
551只玄猫6 小时前
【数据库原理 实验报告1】创建和管理数据库
数据库·sql·学习·mysql·课程设计·实验报告·数据库原理
m0_726965987 小时前
面面面,面面(1)
java·开发语言
IDZSY04307 小时前
AI社交平台进阶指南:如何用AI社交提升工作学习效率
人工智能·学习