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

与君共勉!待续

欢迎指错,一起学习

相关推荐
captain3763 小时前
MyBatis(入门5)其他查询操作
java·数据库·spring boot·mybatis
Novproxy_Z3 小时前
商用代理避坑:如何识别商家拿机房 IP 冒充住宅 IP
java·网络·tcp/ip
夕除4 小时前
Redis 过期策略
redis·笔记·面试
文丑颜不良啊4 小时前
LeetCode1481~1500题目解析
java·leetcode
2601_962885724 小时前
quotes 字段全解:涨跌幅、振幅、换手率的口径与单位
java·前端·spring
前端精髓5 小时前
调用openrouter的免费API模型
java·前端·javascript
步行cgn5 小时前
Spring MVC 拦截器 Interceptor 详解:从执行流程到实战应用
java·spring·mvc
文丑颜不良啊5 小时前
LeetCode1381~1400题目解析
java·leetcode
开开心心_Every5 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
Nuanyt5 小时前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness