好用的开源库
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()方法。