Created
May 8, 2014 07:49
-
-
Save showsky/96c3e12dac027e6059ce to your computer and use it in GitHub Desktop.
Async use handlerThread non-block system async
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public abstract class ThreadTask<Params, Progress, Result> { | |
| private HandlerThread mHandlerThread; | |
| private TaskHandler mHandler; | |
| private TaskHandler mUiHandler; | |
| private Params[] mParams; | |
| public ThreadTask() { | |
| mHandlerThread = new HandlerThread("ThreadTask", android.os.Process.THREAD_PRIORITY_BACKGROUND); | |
| mHandlerThread.start(); | |
| mHandler = new TaskHandler(mHandlerThread.getLooper()); | |
| mUiHandler = new TaskHandler(Looper.getMainLooper()); | |
| } | |
| protected abstract Result doInBackground(Params... params); | |
| protected void onPreExecute() { | |
| } | |
| protected void onProgressUpdate(Progress... values) { | |
| } | |
| protected final void publishProgress(Progress... values) { | |
| mUiHandler.obtainMessage(MESSAGE_PROGRESS, values).sendToTarget(); | |
| } | |
| protected void onPostExecute(Result result) { | |
| } | |
| public final boolean isCancelled() { | |
| return mHandlerThread.isInterrupted(); | |
| } | |
| public final void cancel(boolean mayInterruptIfRunning) { | |
| if (!mHandlerThread.isInterrupted()) { | |
| try { | |
| mHandlerThread.quit(); | |
| mHandlerThread.interrupt(); | |
| } catch (SecurityException e) { | |
| e.printStackTrace(); | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| onCancelled(); | |
| } | |
| protected void onCancelled() { | |
| } | |
| public void execute(Params... params) { | |
| mParams = params; | |
| onPreExecute(); | |
| mHandler.sendEmptyMessage(MESSAGE_INBACKGROUND); | |
| } | |
| private static final int MESSAGE_INBACKGROUND = 0; | |
| private static final int MESSAGE_POSTEXECUTE = 1; | |
| private static final int MESSAGE_PROGRESS = 2; | |
| private class TaskHandler extends Handler { | |
| public TaskHandler(Looper looper) { | |
| super(looper); | |
| } | |
| @SuppressWarnings("unchecked") | |
| @Override | |
| public void handleMessage(Message msg) { | |
| switch (msg.what) { | |
| case MESSAGE_INBACKGROUND: | |
| mUiHandler.obtainMessage(MESSAGE_POSTEXECUTE, doInBackground(mParams)).sendToTarget(); | |
| break; | |
| case MESSAGE_POSTEXECUTE: | |
| onPostExecute((Result) msg.obj); | |
| break; | |
| case MESSAGE_PROGRESS: | |
| onProgressUpdate((Progress[]) msg.obj); | |
| break; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment