Priority Job Queue is an implementation of a Job Queue specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability.
项目地址:https://github.com/path/android-priority-jobqueue
下面通过一个Demo来演示一下如果使用它。
MainActivity 界面布局文件activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <Button android:id="@+id/bt_request" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/http_request" /> <Button android:id="@+id/bt_local" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/local_task" /> </LinearLayout>
TwitterApplication 是Application的一个子类,用来初始化JobManager,代码如下:
package com.example.android_patheventtest.app; import android.app.Application; import android.util.Log; import com.path.android.jobqueue.JobManager; import com.path.android.jobqueue.config.Configuration; import com.path.android.jobqueue.log.CustomLogger; public class TwitterApplication extends Application { private static TwitterApplication instance; private JobManager jobManager; public TwitterApplication() { instance = this; } @Override public void onCreate() { super.onCreate(); configureJobManager(); } private void configureJobManager() { Configuration configuration = 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)); } }) .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); } public JobManager getJobManager() { return jobManager; } public static TwitterApplication getInstance() { return instance; } }
MainActivity 代码
package com.example.android_patheventtest; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.example.android_patheventtest.app.TwitterApplication; import com.example.android_patheventtest.events.DeletedCityEvent; import com.example.android_patheventtest.events.PostedCityEvent; import com.example.android_patheventtest.events.PostingCityEvent; import com.example.android_patheventtest.jobs.PostTweetJob; import com.example.android_patheventtest.tasks.SimpleBackgroundTask; import com.path.android.jobqueue.JobManager; import de.greenrobot.event.EventBus; public class MainActivity extends BaseActivity { private static final String TAG = "MainActivity"; private JobManager jobManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); jobManager = TwitterApplication.getInstance().getJobManager(); findView(); EventBus.getDefault().register(this); } private void findView() { Button bt_request = (Button) findViewById(R.id.bt_request); Button bt_local = (Button) findViewById(R.id.bt_local); bt_request.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { requestData(); } }); bt_local.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doLocalTask(); } }); } protected void doLocalTask() { new SimpleBackgroundTask<String>(this) { @Override protected String onRun() { Log.e(TAG, "SimpleBackgroundTask sleep 8s"); try { Thread.sleep(8000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onSuccess(String result) { // TODO Auto-generated method stub Log.e(TAG, "SimpleBackgroundTask execute success"); } }.execute(); } protected void requestData() { jobManager.addJobInBackground(1, new PostTweetJob("SKY")); } public void onEventMainThread(PostingCityEvent ignored) { Log.i(TAG, "PostingCityEvent status="+ignored.getStatus()); } public void onEventMainThread(PostedCityEvent ignored) { Log.i(TAG, "PostedCityEvent status="+ignored.getStatus()); } public void onEventMainThread(DeletedCityEvent ignored) { Log.i(TAG, "DeletedCityEvent status="+ignored.getStatus()); } @Override protected void onDestroy() { super.onDestroy(); try { EventBus.getDefault().unregister(this); } catch (Throwable t){ //this may crash if registration did not go through. just be safe } } }
定义自己的BaseJob任务,代码如下:
package com.example.android_patheventtest.jobs; import android.util.Log; import com.example.android_patheventtest.events.DeletedCityEvent; import com.example.android_patheventtest.events.PostedCityEvent; import com.example.android_patheventtest.events.PostingCityEvent; import com.path.android.jobqueue.BaseJob; import de.greenrobot.event.EventBus; public class PostTweetJob extends BaseJob { private static final String TAG = "PostTweetJob"; private long localId; private String text; public PostTweetJob(String text) { super(true, true, "post_tweet");//order of tweets matter, we don't want to send two in parallel //use a negative id so that it cannot collide w/ twitter ids //we have to set local id here so it gets serialized into job (to find tweet later on) localId = -System.currentTimeMillis(); this.text = text; } @Override public void onAdded() { // TODO Auto-generated method stub Log.e(TAG, "onAdded"); EventBus.getDefault().post(new PostingCityEvent("posting")); } @Override public void onRun() throws Throwable { // TODO Auto-generated method stub Log.e(TAG, "onRun sleep 6s"); Thread.sleep(6000); EventBus.getDefault().post(new PostedCityEvent("posted")); } @Override protected void onCancel() { // TODO Auto-generated method stub Log.e(TAG, "onCancel"); EventBus.getDefault().post(new DeletedCityEvent("deleted")); } @Override protected boolean shouldReRunOnThrowable(Throwable throwable) { // TODO Auto-generated method stub Log.e(TAG, "shouldReRunOnThrowable"); return false; } }
一下是自定义的3个Event事件对象:
package com.example.android_patheventtest.events; public class PostingCityEvent { private String status; public PostingCityEvent(String status) { this.status = status; } public String getStatus() { return status; } }
package com.example.android_patheventtest.events; public class PostedCityEvent { private String status; public PostedCityEvent(String status) { this.status = status; } public String getStatus() { return status; } }
package com.example.android_patheventtest.events; public class DeletedCityEvent { private String status; public DeletedCityEvent(String status) { this.status = status; } public String getStatus() { return status; } }
最后是SimpleBackgroundTask 类
package com.example.android_patheventtest.tasks; import android.app.Activity; import android.os.AsyncTask; import java.lang.ref.WeakReference; abstract public class SimpleBackgroundTask<T> extends AsyncTask<Void, Void, T> { WeakReference<Activity> weakActivity; public SimpleBackgroundTask(Activity activity) { weakActivity = new WeakReference<Activity>(activity); } @Override protected final T doInBackground(Void... voids) { return onRun(); } private boolean canContinue() { Activity activity = weakActivity.get(); return activity != null && activity.isFinishing() == false; } @Override protected void onPostExecute(T t) { if(canContinue()) { onSuccess(t); } } abstract protected T onRun(); abstract protected void onSuccess(T result); }
目前了解的就这么多,如果你知道更多关于 priority jobqueue的使用方法,欢迎留言!