[Android] AsyncTask
AsyncTask
๋ฐฑ๊ทธ๋ผ์ด๋ ์์ ๊ฒฐ๊ณผ๋ฅผ UI๋ก ์ ๋ฌ
[์ถ์ฒ: https://androidkennel.org/android-networking-tutorial-with-asynctask/]
public class FullTask extends AsyncTask<Params, Progress, Result> { ... }
-
Params
๋ฐฑ๊ทธ๋ผ์ด๋์์ ์คํ๋๋ ํ์คํฌ๋ก ์ ๋ ฅ๋๋ ๋ฐ์ดํฐ -
Progress
๋ฐฑ๊ทธ๋ผ์ด๋ ์ค๋ ๋์ doInBackgroud์์ UI์ค๋ ๋์ onProgressUpdate๋ก ๋ณด๋ผ ์งํ ๋ฐ์ดํฐ -
Result
UI ์ค๋ ๋๋ก ๋ณด๋ด์ง ๊ฒฐ๊ณผ
์ํ
- PENDING: task๊ฐ ์์ง ์คํ๋์ง ์์ ์ํ
- RUNNING: ์คํ์ค์ธ ์ํ
- FINISHED: AsyncTask.onPostExecute()๊น์ง ๋๋ ์ํ
AsyncTask ์ทจ์
task.cancel(true);
- true: isCancelled()๋ก ํ์ธํ ์ ์๋ ํ๋๊ทธ ์ค์ + ์ธํฐ๋ฝํธ
- false: isCancelled()๋ก ํ์ธํ ์ ์๋ ํ๋๊ทธ ์ค์
์ค๋ ๋์ ๋ง์ฐฌ๊ฐ์ง๋ก, ๊ฐ์ ์ข
๋ฃํ ์ ์๋ค.
InterruptedException์ ๋์ง ๋ ์ข
๋ฃ
๊ธด ์์
์์ ์ ํ์ธํ๋ ์ฒดํฌํฌ์ธํธ (๋ฐ๋ณต๋ฌธ์ ์กฐ๊ฑด๋ฌธ์ด๋ ๊ธด ์์
์ฌ์ด)
Flow
Status = PENDING
-
AsyncTask()
- Worker ์์ฑ
mWorker = new WorkerRunnable<Params, Result>() { public Result More ...call() throws Exception { ... return postResult(doInBackground(mParams)); // postResult() : MESSAGE_POST_RESULT ๋ฉ์์ง๋ฅผ ๋ณด๋ } };
- FutureTask ์์ฑ
mFuture = new FutureTask<Result>(mWorker) { @Override protected void More ...done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { ... } } };
- Worker ์์ฑ
-
.execute()
Status = RUNNING
- .onPreExecute() ํธ์ถ
- doInBackground()
exec.execute(mFuture); // -> doInBackground() ์คํ
- .onPreExecute() ํธ์ถ
- doInBackground()
-
publishProgress() ํธ์ถํ๋ ๊ฒฝ์ฐ
MESSAGE_POST_PROGRESS ๋ฉ์์ง ๋ณด๋
onProgressUpdate(); ์คํ -
doInBackground() ์ข ๋ฃ ์
MESSAGE_POST_RESULT ๋ฉ์์ง ๋ณด๋
finish(); ์คํ
-
- finish()
- isCancelled() = true
onCancelled(); ์คํ - isCancelled() = false
onPostExecute(); ์คํ
- isCancelled() = true
Status = FINISHED
AsyncTask์ InternalHandler
private static class More ...InternalHandler extends Handler { public More ...InternalHandler() { super(Looper.getMainLooper()); // Looper-MainLooper } @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void More ...handleMessage(Message msg) { AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // postResult()์์ // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: // publishProgress()์์ result.mTask.onProgressUpdate(result.mData); break; } } }
ThreadPool
Comments