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详解

与君共勉!待续

欢迎指错,一起学习

相关推荐
方华世界11 分钟前
企业级Java AI Agent应用平台
java·开发语言·人工智能
绝世番茄15 分钟前
鸿蒙HarmonyOS ArkTS原生学习:缩放手势实现 PinchToZoom 深度解析
学习·华为·harmonyos·鸿蒙
a11177621 分钟前
SLAM 学习笔记(四)后端(KF BA)
笔记·学习
私人珍藏库34 分钟前
[Android] PocketPal -本地离线AI助手+大模型部署神器
android·人工智能·app·软件·多功能
折哥的程序人生 · 物流技术专研39 分钟前
第8篇:模板方法模式的优缺点与面试高频考点
java·设计模式·面试·模板方法模式·行为型模式·优缺点·扩充系列
XGeFei1 小时前
【Django学习笔记】—— Django 高并发通俗讲解
笔记·学习·django
爱笑鱼1 小时前
Handler(三):主线程、HandlerThread、Binder 线程到底怎么区分?
android
w139548564221 小时前
鸿蒙实战:报告与雷达图 ReportDao
android·华为·harmonyos·鸿蒙系统
六点_dn1 小时前
Linux学习笔记-chmod命令
linux·笔记·学习
那个松鼠很眼熟w1 小时前
4. GB2312字符集,以及字符编码
笔记