IntentService学习
- IntentService
- 常规用法
- 清单注册服务
- 服务内容
- 开启服务
IntentService
一个 HandlerThread工作线程,通过Handler实现把消息加入消息队列中等待执行,通过传递的intent在onHandleIntent中处理任务。(多次调用会按顺序执行事件,服务停止清除消息队列中的消息。)
适用:线程任务按顺序在后台执行,例如下载
不适用:多个数据同时请求
1、IntentService与Service的区别
从属性作用上来说
Service:依赖于应用程序的主线程(不是独立的进程 or 线程)。需要主动调用stopSelft()来结束服务
不建议在Service中编写耗时的逻辑和操作,否则会引起ANR;
IntentService:创建一个工作线程来处理多线程任务。在所有intent被处理完后,系统会自动关闭服务
2、IntentService与其他线程的区别
IntentService内部采用了HandlerThread实现,作用类似于后台线程;
与后台线程相比,IntentService是一种后台服务,优势是:优先级高(不容易被系统杀死),从而保证任务的执行。
对于后台线程,若进程中没有活动的四大组件,则该线程的优先级非常低,容易被系统杀死,无法保证任务的执行
常规用法
清单注册服务
<service android:name=".SerialService"><intent-filter><action android:name="android.service.newland.serial" /></intent-filter></service>
服务内容
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);}@Overrideprotected 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();}}}
}
开启服务
SerialService.startSS(this);
感谢互联网
适合阅读文章分享
Android IntentService详解
与君共勉!待续
欢迎指错,一起学习