Android Priority Job Queue 入门

2024-08-30 04:48

本文主要是介绍Android Priority Job Queue 入门,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 简介
Android Priority Job Queue是一款专门为Android平台编写,实现了Job Queue的后台任务队列类库,能够轻松的在后台执行定时任务,提高用户体验和应用的稳定性。
github地址:https://github.com/path/android-priority-jobqueue
2. 背景
几乎所有的应用程序都存在后台线程工作。这些“背景任务”需要保持应用程序响应性和鲁棒性,特别是在不利的情况下(如有限的网络连接)。在安卓应用中,有几种方法来实现后台工作:
1) 异步任务:
使用异步任务是最简单的方法,但它与activity生命周期紧密耦合。如果Activity生命周期发生了改变,比如用户旋转了它的屏幕,那么Activity重新加载,那么后台任务可能会被停止。
2) 使用service:
使用服务可以很好地处理界面逻辑,但是,随着事物的增加,可能需要一个线程池来安排队列请求道磁盘中,而且需要考虑任务的优先级和并发时的并发问题
作业队列提供了一个很好的框架来完成上述所有的工作。当确定了你的后台任务的工作时,将它们作为Job添加到你jobmanager实例。Job Manage会照顾优先级,持久性,负载平衡,延迟,网络控制,分组等,它还提供了一个很好的生命周期,为工作提供一个更好的,一致的用户体验。
3. 使用(基于android studio)
1.添加依赖

compile 'com.birbit:android-priority-jobqueue:1.3.5'

2.创建Application并配置JobManager

public class AppApplication extends Application {private JobManager jobManager;public static AppApplication instance;@Overridepublic void onCreate() {super.onCreate();configureJobManager();}public AppApplication(){instance=this;}public JobManager getJobManager() {return jobManager;}public static AppApplication getInstance() {return instance;}private void configureJobManager() {Configuration configuration = new Configuration.Builder(this).customLogger(new CustomLogger() {private static final String TAG = "JOBS";@Overridepublic boolean isDebugEnabled() {return true;}@Overridepublic void d(String text, Object... args) {Log.d(TAG, String.format(text, args));}@Overridepublic void e(Throwable t, String text, Object... args) {Log.e(TAG, String.format(text, args), t);}@Overridepublic void e(String text, Object... args) {Log.e(TAG, String.format(text, args));}}).minConsumerCount(1)//always keep at least one consumer alive.maxConsumerCount(3)//up to 3 consumers at a time.loadFactor(3)//3 jobs per consumer.consumerKeepAlive(120)//wait 2 minute.build();jobManager = new JobManager(this, configuration);}
}

3.创建Job任务

public class MJob extends Job {public static final int PRIORITY = 1;private String text;public MJob(String text) {// This job requires network connectivity,// and should be persisted in case the application exits before job is completed.super(new Params(Integer.parseInt(text)).requireNetwork().persist());this.text = text;Log.i("job",text+"  goin");}@Overridepublic void onAdded() {// Job has been saved to disk.// This is a good place to dispatch a UI event to indicate the job will eventually run.// In this example, it would be good to update the UI with the newly posted tweet.Log.i("job",text+"  Onadded");}@Overridepublic void onRun() throws Throwable {// Job logic goes here. In this example, the network call to post to Twitter is done here.// All work done here should be synchronous, a job is removed from the queue once// onRun() finishes.Log.i("job",text+"  onRun");}@Overrideprotected RetryConstraint shouldReRunOnThrowable(Throwable throwable, int runCount,int maxRunCount) {// An error occurred in onRun.// Return value determines whether this job should retry or cancel. You can further// specify a backoff strategy or change the job's priority. You can also apply the// delay to the whole group to preserve jobs' running order.return RetryConstraint.createExponentialBackoff(runCount, 1000);}@Overrideprotected void onCancel() {}
}
任务调用执行Job时会依次执行onAdded(),onRun().
4.MainActivity 
public class MainActivity extends AppCompatActivity {private JobManager jobManager;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);jobManager = AppApplication.getInstance().getJobManager();Button btn_start = (Button)findViewById(R.id.btn_start);btn_start.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {jobManager.addJobInBackground(new MJob("1"));jobManager.addJobInBackground(new MJob("2"));jobManager.addJobInBackground(new MJob("3"));jobManager.addJobInBackground(new MJob(""));jobManager.addJobInBackground(new MJob(""));jobManager.addJobInBackground(new MJob(""));}});

4.执行结果
初始化所有的job
这里写图片描述
执行前三个Job的Onadd()方法,同时执行Job1的OnRun()方法。
这里写图片描述
在执行完一个onAdd()方法后接着会调用队列中的第一个的OnAdd()方法。

5.分析
从Log中可以看到这个框架有一套自己的调度算法:
这里写图片描述
事实上,感觉这套框架其实跟Java的线程池差不多,都是来安排队列任务的优先级,调度方案,不过这套框架使用比较简单。
推荐一个Android的线程池博客:http://www.xuanyusong.com/archives/2439

这篇关于Android Priority Job Queue 入门的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1119835

相关文章

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

springboot如何通过http动态操作xxl-job任务

《springboot如何通过http动态操作xxl-job任务》:本文主要介绍springboot如何通过http动态操作xxl-job任务的问题,具有很好的参考价值,希望对大家有所帮助,如有错... 目录springboot通过http动态操作xxl-job任务一、maven依赖二、配置文件三、xxl-

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(

Redis 配置文件使用建议redis.conf 从入门到实战

《Redis配置文件使用建议redis.conf从入门到实战》Redis配置方式包括配置文件、命令行参数、运行时CONFIG命令,支持动态修改参数及持久化,常用项涉及端口、绑定、内存策略等,版本8... 目录一、Redis.conf 是什么?二、命令行方式传参(适用于测试)三、运行时动态修改配置(不重启服务

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局

Android ViewBinding使用流程

《AndroidViewBinding使用流程》AndroidViewBinding是Jetpack组件,替代findViewById,提供类型安全、空安全和编译时检查,代码简洁且性能优化,相比Da... 目录一、核心概念二、ViewBinding优点三、使用流程1. 启用 ViewBinding (模块级

MySQL DQL从入门到精通

《MySQLDQL从入门到精通》通过DQL,我们可以从数据库中检索出所需的数据,进行各种复杂的数据分析和处理,本文将深入探讨MySQLDQL的各个方面,帮助你全面掌握这一重要技能,感兴趣的朋友跟随小... 目录一、DQL 基础:SELECT 语句入门二、数据过滤:WHERE 子句的使用三、结果排序:ORDE

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

Python中OpenCV与Matplotlib的图像操作入门指南

《Python中OpenCV与Matplotlib的图像操作入门指南》:本文主要介绍Python中OpenCV与Matplotlib的图像操作指南,本文通过实例代码给大家介绍的非常详细,对大家的学... 目录一、环境准备二、图像的基本操作1. 图像读取、显示与保存 使用OpenCV操作2. 像素级操作3.