http://developer.android.com/reference/android/os/AsyncTask.html
에 보면
AsyncTask must be subclassed to be used. The subclass will override at least
one method (
Here is an example of subclassing:
doInBackground(Params...)),
and most often will override a second one (onPostExecute(Result).)Here is an example of subclassing:
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)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }
요렇게 만들고
Once created, a task is executed very simply:new DownloadFilesTask().execute(url1, url2, url3);
요렇게 쓴다고 되어 있다.
안드로이드 포스팅 중에 고수라 할 수 있는
http://tigerwoods.tistory.com/20
이곳에 가면 풀소스를 구할 수 있다.
XML이야 버튼이랑 텍스트뷰 버튼 하나 기본으로 달아 주면 소스를 실행할 수 있다.
package com.example.test1;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class AsyncTaskDemo extends Activity implements View.OnClickListener {
ProgressBar progressBar;
TextView textResult;
Button btnExecuteTask;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
textResult = (TextView) findViewById(R.id.textView2);
btnExecuteTask = (Button) findViewById(R.id.button1);
btnExecuteTask.setOnClickListener(this);
}
public void onClick(View v) {
// AsynchTask를 상속하는 DoComplecatedJob 클래스를 생성하고
// execute(...) 명령으로 background작업을 시작함.
// (예제에 구현된 AsynchTask는 String 형의 인자를 받음)
new AsyncTaskTestClass().execute("100", "200", "309", "404", "505");
}
// AsyncTask클래스는 항상 Subclassing 해서 사용 해야 함.
// 사용 자료형은
// background 작업에 사용할 data의 자료형: String 형
// background 작업 진행 표시를 위해 사용할 인자: Integer형
// background 작업의 결과를 표현할 자료형: Long
private class AsyncTaskTestClass extends AsyncTask {
// 이곳에 포함된 code는 AsyncTask가 execute 되자 마자 UI 스레드에서 실행됨.
// 작업 시작을 UI에 표현하거나
// background 작업을 위한 ProgressBar를 보여 주는 등의 코드를 작성.
@Override
protected void onPreExecute() {
textResult.setText("Background 작업 시작 ");
super.onPreExecute();
}
// UI 스레드에서 AsynchTask객체.execute(...) 명령으로 실행되는 callback
@Override
protected Long doInBackground(String... strData) {
long totalTimeSpent = 0;
// 가변인자의 갯수 파악 (이 예제에서는 5개)
int numberOfParams = strData.length;
// 인자들을 이용한 어떤 작업을 처리를 함
for (int i = 0; i < numberOfParams; i++) {
// 각 인자를 이용한 복잡한 Task 실행함.
// 예제에서는 인자로 전달된 시간만큼 sleep
SystemClock.sleep(new Integer(strData[i]));
// background 작업에 걸린시간을 누산해 리턴함
totalTimeSpent += new Long(strData[i]);
// onProgressUpdate callback을 호출 해
// background작업의 실행경과를 UI에 표현함
publishProgress((int) (((i + 1) / (float) numberOfParams) * 100));
}
return totalTimeSpent;
}
// onInBackground(...)에서 publishProgress(...)를 사용하면
// 자동 호출되는 callback으로
// 이곳에서 ProgressBar를 증가 시키고, text 정보를 update하는 등의
// background 작업 진행 상황을 UI에 표현함.
// (예제에서는 UI스레드의 ProgressBar를 update 함)
@Override
protected void onProgressUpdate(Integer... progress) {
progressBar.setProgress(progress[0]);
}
// onInBackground(...)가 완료되면 자동으로 실행되는 callback
// 이곳에서 onInBackground가 리턴한 정보를 UI위젯에 표시 하는 등의 작업을 수행함.
// (예제에서는 작업에 걸린 총 시간을 UI위젯 중 TextView에 표시함)
@Override
protected void onPostExecute(Long result) {
textResult.setText("Background 작업에 걸린 총 시간: " + new Long(result).toString() + "m초");
}
// AsyncTask.cancel(boolean) 메소드가 true 인자로
// 실행되면 호출되는 콜백.
// background 작업이 취소될때 꼭 해야될 작업은 여기에 구현.
@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
}
}
쓰레드 9, 10은 언젠가 프로젝트에 적용하면서 포스팅 하겠다.
댓글 없음:
댓글 쓰기
국정원의 댓글 공작을 지탄합니다.