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 分钟前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心1 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心1 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
SimonKing2 小时前
OpenCode AI辅助编程,不一样的编程思路,不写一行代码
java·后端·程序员
FastBean3 小时前
Jackson View Extension Spring Boot Starter
java·后端
Kapaseker3 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴4 小时前
Android17 为什么重写 MessageQueue
android
Seven974 小时前
剑指offer-79、最⻓不含重复字符的⼦字符串
java
皮皮林55113 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河13 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化