본문 바로가기

프로그래밍/Android

AsyncTask 이해하기

AsyncTask : 1.5에 추가된 유틸리티 클래스

UI 쓰레드를 위한 녀석, 이 클래스는 태스크 생성을 간단히 할 수 있음. 

 

google예제)

ref> http://developer.android.com/reference/android/os/AsyncTask.html

 

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }

protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

 

태스크를 생성하고, 워커쓰레드를 수행~

new DownloadFilesTask().execute(url1, url2, url3);

 

수행시 사용될 파라미터 타입을 지정해야 하는데,

태스크 실행시 사용할 파라미터 타입, 진행 중에 사용할 타입, 리턴용 타입으로 세가지 타입을

정의할 수 있다.

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }

첫번째 인자는 UI 쓰레드에서 execute() 메쏘드 호출시, doInBackground() 입력 타입이고,
두번째는 워커 태스크내의 publishProgress(), onProgressUpdate() 에서 입력하는 타입,
세번째는 워커 태스크내의 doInBackground()의 리턴타입을 의미한다.

예제에서는 url, int, long 사용했는데, 이 처럼 원하는 데이터를 사용해 처리하면 된다.

 

 

 

태스크가 실행되면 아래의 순서로 수행된다.

 

1. onPreExecute() : 태스크가 실행되면 가장 처음 UI 쓰레드에서 수행된다.

2. doInBackground( Params ... ) 은 onPreExecute() 메쏘드 종료 후 워커쓰레드에서 수행됨.

비동기적으로 태스크가 백그라운드로 동작하게 되는데, 동작 중 필요한 정보는

publishProgress( Progress,,) 를 통해 UI 쓰레드로 onProgressUpdate( ) 를

전달하게 된다.

리턴값은 onPostExecute( Result) 로 전송됨.

3. onProgressUpdate( Progress ... ) : UI 쓰레드에서 수행되며, 태스크에서 전달하는 값이다.

4. onPostExecute( Result ) : 태스크 종료 시 호출

 

태스크는 UI 쓰레드(메인쓰레드) 에서만 생성할 수 있다.

execute(Params...) 는 UI 쓰레드에서 호출해야 한다.

onPreExecute(), onPostExecute(), doInBackground(), onProgressUpdate() 를 직접 호출하지 말것.

한번만 실행될 수 있음.( 이미 태스크가 수행중이면 익셈션 발생)

 

기타 public 메쏘드 : 

Public Methods

public final boolean cancel (boolean mayInterruptIfRunning)

Since: API Level 3

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

Parameters

mayInterruptIfRunning

true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.

Returns

  • false if the task could not be cancelled, typically because it has already completed normally; true otherwise

See Also

public final AsyncTask<Params, Progress, Result> execute (Params... params)

Since: API Level

Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it. This method must be invoked on the UI thread.

Parameters

params

The parameters of the task.

Returns

  • This instance of AsyncTask.

Throws

IllegalStateException

If getStatus() returns either RUNNING or FINISHED.

public final Result get ()

Since: API Level 3

Waits if necessary for the computation to complete, and then retrieves its result.

Returns

  • The computed result.

Throws

CancellationException

If the computation was cancelled.

ExecutionException

If the computation threw an exception.

InterruptedException

If the current thread was interrupted while waiting.

public final Result get (long timeout, TimeUnit unit)

Since: API Level 3

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result.

Parameters

timeout

Time to wait before cancelling the operation.

unit

The time unit for the timeout.

Returns

  • The computed result.

Throws

CancellationException

If the computation was cancelled.

ExecutionException

If the computation threw an exception.

InterruptedException

If the current thread was interrupted while waiting.

TimeoutException

If the wait timed out.

public final AsyncTask.Status getStatus ()

Since: API Level 3

Returns the current status of this task.

Returns

  • The current status.

public final boolean isCancelled ()

Since: API Level 3

Returns true if this task was cancelled before it completed normally.

Returns

  • true if task was cancelled before it completed

See Also

 

 

사용법은 별게 없는데, 지정된 타입으로 execute( 인자, 인자, .... ) 형태로 호출해 주고,

백그라운드로 처리될 작업을 doInBackground( 타입... ) 에 구현해 주면 된다.

 

protected 리턴타입 doInBackground( 입력타입... data ) {

// 인자의 갯수를 가져오고

int num = data.legth;

 

// 갯수만큼 처리

for(int i = 0; i< num ; i++ ) {

// 작업

}

 

return 리턴값;

}

 

처리 중 중간 결과(progress)를 알릴필요가 있는 경우 publishProgress()를 호출해 주면 된다.

'프로그래밍 > Android' 카테고리의 다른 글

투명한 레이아웃 만들기  (0) 2009.11.18
메시지 핸들러 사용하기  (0) 2009.11.16
리시버를 통한 sms데이터 가져오기  (0) 2009.11.16
Broadcast/BroadcastReceiver  (0) 2009.11.11
AlarmManger 사용  (0) 2009.11.10
테마설정하기  (0) 2009.11.09
타이틀바 없애기  (0) 2009.11.09
상태바 알림 처리  (0) 2009.11.09
Toast View 만들기  (0) 2009.11.09
AlertDialog 만들기  (0) 2009.11.06