티스토리 뷰

dev/android

AsyncTask

altvirus 2011. 9. 30. 13:46
###java
package com.altvirus;

import java.util.ArrayList;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MyAsyncTask extends ListActivity{
private static String[] items={"aaa", "bbb", "ccc", "ddd", "eee", "fff"};
private ArrayAdapter<String> aa;
private ArrayList<String> al = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, al);
this.setListAdapter(aa);
new AddStringTask().execute(1,2);
}
class AddStringTask extends AsyncTask<Integer, String, Long>{
        @Override
        protected Long doInBackground(Integer... unused){
        
         for(int i=0; i<items.length; i++){
                publishProgress(items[i]);
                SystemClock.sleep(1000);
            }
            return 100L;
        }
        

//doInBackground() 메소드에서 publishProgress() 메소드를 호출하면
        //onProgressUpdate() 메소드에서 인자로 넘겨준 값을 받게된다
        //(사용자 인터페이스에서 실행되므로 주의)
        @Override
        protected void onProgressUpdate(String... item){
         al.add(item[0]);
         aa.notifyDataSetChanged();
        }
        
        //doInBackground() 메소드의 작업이 완료된 직후 호출됨
        @Override
        protected void onPostExecute(Long fromDIB){
        
            Toast.makeText(MyAsyncTask.this, "Done!", Toast.LENGTH_SHORT).show();
        }
    }

'dev > android' 카테고리의 다른 글

안드로이드 UI들 모음..  (0) 2011.11.02
AsyncTask  (1) 2011.09.30
LoadImageFromUrl  (0) 2011.01.10
공지사항