AsyncTask
: 백그라운드 작업을 하는데 만드는 쓰레드, 핸들러 등을 대신 만들어주는 도우미 클래스
Params : 실행시에 전달할 인수 타입.
Progress : 매 작업 단계마다 진행 상태를 표기하기 위한 타입
Result : 작업 결과로 리턴될 타입
void onPreExecute ()
-> 작업 시작되기 전 호출. UI 스레드에서 실행. 보통 초기화작업
Result doInBackground (Params ... params)
-> 배경 작업을 수행. 분리된 스레드에서 실행.
execute 메서드로 전달한 작업거리가 params 인수로 전달됨. (배열 타입으로)
하나의 인수만 필요하면 params[0]만 사용
작업 중에 publishProgress 메서드를 호출하여 작업 경과를 UI 스레드로 보고 가능
void onProgressUpdate (Progress ...values)
-> doInBackground에서 publicProgress 메서드를 호출할 때 작업 경과 표시를 위해
호출되며 UI 스레드에서 실행. 프로그래스 바에 진행 상태를 표시하는 역할
void onPostExecute (Result result)
-> 백그라운드 작업이 끝난 후 UI 스레드에서 실행. 인수로 작업 결과 전달.
취소되거나 예외 발생시 null 전달
void onCancelled ()
-> cancel 메서드로 작업 취소했을 때 호출되며 UI 스레드에서 실행
작업 시작할 때는 AsyncTask 객체를 UI 스레드에서 생성한 후 다음 메서드 호출
!! 반드시 UI 스레드에서 호출 !!
AsyncTask <Params, Progress, Result> execute (Params... params)
boolean cancel (boolean mayInterruptIfRunning)
boolean isCancelled()
-> 작업을 취소하라고 지시.
작업 시작 전에는 취소 성공한 것으로 return 됨.
Result get([long timeout, TimeUnit unit])
-> 작업 완료되기까지 대기하며 작업 결과를 돌려 받는다. 타임아웃값 지정 가능
AsyncTask.Status getStatus()
-> 작업의 현재 상태 조사. 시작되지 않은 상태면 PENDING 리턴. 이미 실행중이면 RUNNING,
완료되었다면 FINISHED가 리턴
메인 스레드 | 작업 스레드 |
| execute onPrepareExecute() // 작업 스레드 작동 onProgressUpdate() // 메인에서 한번 작동 onPostExecute() // 메인에서 한번 작동 작업 완료 | doInBackground(){ while(){ //To do publishProgress() } return result; } |
================================== ex ============================================
ProgressDialog mProgress;
new AccumulateTask().execute(100);
class AccumulateTask extends AsyncTask<Integer, Integer, Integer> {
protected void onPreExecute(){
mValue = 0;
mProgress = new ProgressDialog(.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();
}
}
=====================================================================================
댓글 없음:
댓글 쓰기