Back to project page foreman.
The source code is released under:
GNU General Public License
If you think the Android project foreman listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.ajaso.android.foreman; //w w w. j a v a2 s. co m import android.annotation.SuppressLint; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import com.ajaso.android.stream.StreamProgress; import java.util.*; /** * Author: Adam J Jaso, Jr * Copyright: Adam J Jaso, Jr 2014 */ public class Foreman { public static final String tag = Foreman.class.getSimpleName(); private static Foreman instance; private Map<Context, List<Work>> current = Collections.synchronizedMap(new WeakHashMap<Context, List<Work>>()); private Foreman() {} public synchronized static Foreman get() { if (instance == null) { instance = new Foreman(); } return instance; } public void start(Context context, Job job) { start(context, job, false); } @SuppressLint("NewApi") public void start(Context context, Job job, boolean serial) { if (job == null) { return; } Work w; if (current.get(context) == null) { final List<Work> list = new ArrayList<Work>(); current.put(context, list); w = new Work(job, list); list.add(w); } else { final List<Work> list = current.get(context); w = new Work(job, list); list.add(w); } if (serial || Build.VERSION.SDK_INT < 11) { w.execute(); } else { w.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } public void cancel(Context context) { final List<Work> ws = current.get(context); if (ws != null) { for (final Work w : ws) { w.cancel(true); } } } private class Work extends AsyncTask<Void, Integer, Result> implements StreamProgress { private final Job r; private final List<Work> ws; private boolean hasConnected = false; public Work(Job r, List<Work> ws) { this.ws = ws; this.r = r; this.r.remoteProgress(this); } @Override protected Result doInBackground(Void... voids) { return this.r.handleRequest(); } @Override public void onProgress(Object job, int progress) { publishProgress(progress); } @Override protected void onPreExecute() { this.r.connecting(); } @Override protected void onProgressUpdate(Integer... progress) { if (!hasConnected) { this.r.connected(); this.hasConnected = true; } this.r.progress(progress[0]); } @Override protected void onCancelled() { this.r.cancelled(); } @Override protected void onPostExecute(Result result) { this.r.callback(result); synchronized (this.ws) { if (this.ws != null) { this.ws.remove(this); } } } } }