AsyncTask 클래스

작업 스레드와 관련된 복잡한 부분을 쉽게 처리해주는 클래스(API15 버전부터 추가)

Handler 클래스나 Progress Dialog 대신 AsyncTask 클래스를 이용하면 한번에 처리 가능


AsyncTask


1. 레이아웃


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.progdv.asynctask.MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/btnTask"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="데이터베이스 엑세스"/>

</LinearLayout>
</RelativeLayout>





2. 메인 액티비티


package com.progdv.asynctask;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
Button btnTask;
ProgressDialog dialog;
int pValue;

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

btnTask = (Button)findViewById(R.id.btnTask);
btnTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MyAsyncTask().execute(100);
}
});
}

public class MyAsyncTask extends AsyncTask<Integer, Integer, String>{

@Override
protected void onPreExecute() { // 가장 처음에 호출되는 메서드
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("처리중...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "취소",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}

@Override
protected String doInBackground(Integer... params) {
while(pValue < params[0]){
pValue++;
publishProgress(pValue);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pValue = 0;
return "다운로드 완료";
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);

dialog.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}
}




데이터베이스 액세스 버튼을 누르면 게이지가 올라간 뒤 끝나면 종료된다.









Posted by netyhobby
,