메시지 기반의 쓰레드 이용은 핸들러를 사용하면서 코드가 복잡해지는 문제가 있다. 백그라운드 작업을 좀 더 쉽게 하고 싶다면 AsyncTask 클래스를 사용할 수 있다.


AsyncTask 객체를 만들고 execute 메소드를 실행하면 이 객체는 정의된 백그라운드 작업을 수행하고 필요한 경우에 그 결과를 메인 쓰레드에서 실행한다.


메소드명 

설명 

 execute

  • 백그라운드 작업 수행

 cancel

  • 백그라운드 작업 취소

doInBackground

  • 새로 만든 쓰레드에서 백그라운드 작업 수행
  • execute 메소드를 호출할 때 사용된 파라미터를 배열로 전달받음

onPreExecute

  • 백그라운드 작업 수행 전에 호출됨

onProgressUpdate

  • 백그라운드 작업의 진행 상태를 표시하기 위해 호출됨
  • 작업 수행 중간 중간에 UI 객체에 접근하는 경우에 사용됨
  • 이 메소드가 호출되려면 publishProgress 메소드를 호출하여야 함

onPostExecute

  • 백그라운드 작업이 끝난 후 호출됨

 getStatus

  • 작업의 진행 상황을 리턴
  • 상태는 PENDING, RUNNUNG, FINISHED로 표현됨


아래는 백그라운드에서 프로그레스바를 진행시키는 코드이다.

public class MainActivity extends Activity {

	TextView textView01;
	ProgressBar progress;
	BackgroundTask task;
	int value;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView01 = (TextView) findViewById(R.id.textView01);
        progress = (ProgressBar) findViewById(R.id.progress);

        // 실행 버튼 이벤트 처리
        Button executeBtn = (Button) findViewById(R.id.executeBtn);
        executeBtn.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		// 새로운 Task 객체를 만들고 실행
        		task = new BackgroundTask();
        		// 백그라운드 작업 수행
        		// doInBackground에 100을 전달
        		task.execute(100);
        	}
        });

        // 취소 버튼 이벤트 처리
        Button cancelBtn = (Button) findViewById(R.id.cancelBtn);
        cancelBtn.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		task.cancel(true);
        	}
        });
    }


    /**
     * 새로운 Task 객체를 정의
     */
    class BackgroundTask extends AsyncTask<Integer, Integer, Integer> {
    	protected void onPreExecute() {
    		value = 0;
    		progress.setProgress(value);
    	}

    	protected Integer doInBackground(Integer ... values) {
    		//values[0] equal to 100;
    		while (isCancelled() == false) {
    			value++;
    			if (value >= 100) {
    				break;
    			} else {
    				publishProgress(value);
    			}

    			try {
    				Thread.sleep(100);
    			} catch (InterruptedException ex) {}
    		}

    		return value;
    	}

    	protected void onProgressUpdate(Integer ... values) {
    		progress.setProgress(values[0].intValue());
    		textView01.setText("Current Value : " + values[0].toString());
    	}

    	protected void onPostExecute(Integer result) {
    		progress.setProgress(0);
    		textView01.setText("Finished.");
    	}

    	protected void onCancelled() {
    		progress.setProgress(0);
    		textView01.setText("Cancelled.");
    	}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


+ Recent posts