이 블로그 검색

2011년 10월 19일 수요일

안드로이드 비동기 처리 기법 - AsyncTask

1. 객체.execute() 메서드로 시작한다. 
2. doInBackGround 에서 서버 연동이나 다운로드 등의 작업을 한다. (Thread에서 run() 함수)
3. onPostExecute 에서 UI 업데이트 작업을 한다. (Handler의 handleMessage() 함수)

 new AsyncTask<String, Integer, String>() {

/* doInBackGround 에서 백데이터 작업(다운로드 등)을 한다. - 분리된 쓰레드에서 작업  
protected String doInBackground(String... arg0) {
RWServerNetwork network = new RWServerNetwork();
HashMap<String, String> params = new HashMap<String, String>();
params.put("recommend_count", "15");
params.put("best_count", "15");

try {
network.getData(Define.SERVER_URL_FEATUREDLIST,        RWServerNetwork.getHeader(FeaturedActivity.this), params, false);
if (network.parser("result")!=null && network.parser("result").equals("700")) {
Element e = network.getParser();
int cnt = Util.parseXmlDocument(e, "recommend").length;
recommendInfoList.clear();
for (int i=0;i<cnt;i++) {
recommendInfoList.add(new Book(e,"recommend", i));
}

cnt = Util.parseXmlDocument(e, "best").length;
bestInfoList.clear();
for (int i=0;i<cnt;i++) {
bestInfoList.add(new Book(e,"best", i));
}
return "";
}
}catch (Exception e) {
Util.logError(e);
}
return null;
}
*/ 분리된 쓰레드에서 작업

/* onPostExecute 에서 최종 UI갱신 작업 - UI (main)쓰레드에서 작업
protected void onPostExecute(String tempData) {
RWDialog.closeProgress(FeaturedActivity.this);
if (tempData == null) {
RWDialog.showDialog(FeaturedActivity.this, RWDialog.SERVER_CONNECT_ERROR);
}
refreshData();
}
}.execute();   <-- 시작

댓글 없음:

댓글 쓰기