博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android上传队列使用
阅读量:6331 次
发布时间:2019-06-22

本文共 4510 字,大约阅读时间需要 15 分钟。

好用的开源库

compile 'com.birbit:android-priority-jobqueue:2.0.1'复制代码

1.自定义Application

private JobManager jobManager;private void configureJobManager() {    Configuration.Builder builder = new Configuration.Builder(this)            .customLogger(new CustomLogger() {                private static final String TAG = "JOBS";                @Override                public boolean isDebugEnabled() {                    return true;                }                @Override                public void d(String text, Object... args) {                    Log.d(TAG, String.format(text, args));                }                @Override                public void e(Throwable t, String text, Object... args) {                    Log.e(TAG, String.format(text, args), t);                }                @Override                public void e(String text, Object... args) {                    Log.e(TAG, String.format(text, args));                }                @Override                public void v(String text, Object... 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    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {        builder.scheduler(FrameworkJobSchedulerService.createSchedulerFor(this,                MyJobService.class), true);    }    jobManager = new JobManager(builder.build()); }public synchronized JobManager getJobManager() {    if (jobManager == null) {        configureJobManager();    }    return jobManager; } public static MyApp getInstance() {    return myApp; }复制代码

2.重写FrameworkJobSchedulerService

public class MyJobService extends FrameworkJobSchedulerService {    @NonNull    @Override    protected JobManager getJobManager() {        return MyApp.getInstance().getJobManager();    } }复制代码

3.自定义所需业务逻辑的Job

public class MyJob extends Job {    private Handler mHandler;    private String city;    protected MyJob(Params params, Handler handler,String city) {        super(params);        this.mHandler = handler;        this.city = city;    }    @Override    public void onAdded() {        Log.w("日志", "onAdded: 添加了");    }    @Override    public void onRun() throws Throwable {        Log.w("日志", "onRun: 执行");        OkHttpClient client = new OkHttpClient();        client.setConnectTimeout(30 * 1000, TimeUnit.MILLISECONDS);        client.setWriteTimeout(30*1000,TimeUnit.MILLISECONDS);        Request request = new Request.Builder()                .url(city.equals("北京")?"http://www.sojson.com/open/api/weather/json.shtml?city=北京":"http://www.weather.com.cn/data/sk/101110101.html")                .build();        Response response = client.newCall(request).execute();        ResponseBody body = response.body();        byte[] bytes = body.bytes();        String get = new String(bytes,"UTF-8");        Log.w("日志", "onRun: "+get);    }    @Override    protected void onCancel(int cancelReason, @Nullable Throwable throwable) {    }    @Override    protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {        Log.w("日志", "shouldReRunOnThrowable: 异常情况再次运行");        return null;    }}复制代码

4.将Job加入队列

public class MainActivity extends AppCompatActivity {        JobManager jobManager;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        jobManager = MyApp.getInstance().getJobManager();        post.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                query();            }        });    }    private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            Result result = (Result) msg.obj;            if (result.getStatus() == 200) {                Log.w("日志", "handleMessage: " + result.getMessage());            }        }    };    private void query() {        // 开启网络线程执行该Job        // Params参数越大优先级越高        MyJob job = new MyJob(new Params(7).requireNetwork(), handler, "北京");        jobManager.addJobInBackground(job);        MyJob job1 = new MyJob(new Params(7).requireNetwork(), handler, "上海");        jobManager.addJobInBackground(job1);    }}复制代码

job被添加到队列中时会立即执行onAdded()方法,而后在队列中FIFO,依次执行onRun()方法。

转载地址:http://gzboa.baihongyu.com/

你可能感兴趣的文章
unidac 执行Execute后取得受影响行数。
查看>>
C#中的集合类——HashTable
查看>>
如何使用Nexus搭建Maven私服
查看>>
AC日记——Dining poj 3281
查看>>
AC日记——[ZJOI2009]狼和羊的故事 bzoj 1412
查看>>
搭建SVN服务器
查看>>
Linux中的 awk查找日志中的相关记录
查看>>
算法笔记-经典链表操作案例
查看>>
git commit之后,想撤销commit
查看>>
HTML
查看>>
12周总结
查看>>
Python学习笔记十 IO编程
查看>>
C Primer+Plus(十七)高级数据表示(三)
查看>>
51nod 1183 编辑距离
查看>>
Codeforces 221 A. Little Elephant and Function
查看>>
[HNOI2008]Cards
查看>>
算法(4) 排序
查看>>
主成分分析 R语言
查看>>
C# Enum,Int,String的互相转换
查看>>
【原创】自动结束进程脚本
查看>>