다크엔젤리
2013. 1. 16. 09:53
Android AsyncTask
1. Android AsyncTask Thread
- 백그라운드 작업을 하기 위해서는 스레드, 핸들러 등을 각각 만들어야 하고 작업 중에 핸들러를 주기적으로 호출해야 하는 번거로움이 있는데 이 작업을 대신 수행해 주는 도우미 클래스
- AsyncTask<Params, Progress, Result> 인수 타입
a. Params : 실행시에 전달할 인수의 타입이다. 즉 배경 작업거리이다.
b. Progress : 매 작업 단계마다 진행 상태를 표기하기 위한 타입니다.
c. Result : 작업의 결과로 리턴될 타입니다.
2. AsyncTask 순행 구조

3. 참고 사이트 : http://tigerwoods.tistory.com/28
4. 예제 소스
public class C16_LongTime5 extends Activity {
int mValue;
TextView mText;
ProgressDialog mProgress;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.c16_longtime);
mText = (TextView)findViewById(R.id.text);
}
public void mOnClick(View v) {
new AccumulateTask().execute(100);
}
class AccumulateTask extends AsyncTask {
protected void onPreExecute() {
mValue = 0;
mProgress = new ProgressDialog(C16_LongTime5.this);
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setTitle("Updating");
mProgress.setMessage("Wait...");
mProgress.setCancelable(false);
mProgress.setProgress(0);
mProgress.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
cancel(true);
}
});
mProgress.show();
}
protected Integer doInBackground(Integer... arg0) {
while (isCancelled() == false) {
mValue++;
if (mValue <= 100) {
publishProgress(mValue);
} else {
break;
}
try { Thread.sleep(50); } catch (InterruptedException e) {;}
}
return mValue;
}
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
mText.setText(Integer.toString(progress[0]));
}
protected void onPostExecute(Integer result) {
mProgress.dismiss();
}
protected void onCancelled() {
mProgress.dismiss();
}
}
}