728x90

파일 다운로드 함수를 구현하기에 앞서 AsyncTask 다운로드 상태바 표시되는 예제다.

동영상 강좌 듣는 것을 테스트 하면서 명칭 일부를 수정한 거다.

AsyncTask 개념 설명은 http://link2me.tistory.com/1031 을 참조하면 된다.

실제 코드 구현하면서 에러 발생하는 부분 등을 같이 포함해서 기록해 두고 있다.


AsyncTask_ex01.zip


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.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    ProgressBar pBar;
    DownloadFileAsyncTask downloadFileAsyncTask;

    int value;

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

        textView = (TextView)findViewById(R.id.txtView01);
        pBar = (ProgressBar)findViewById(R.id.progressBar);

        Button btn_Start = (Button)findViewById(R.id.btnStart);
        btn_Start.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                // 백그라운드 객체를 만들어줌
                downloadFileAsyncTask = new DownloadFileAsyncTask();
                downloadFileAsyncTask.execute();
            }
        });

        Button btn_Cancel = (Button)findViewById(R.id.btnCancel);
        btn_Cancel.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                downloadFileAsyncTask.cancel(true);
            }
        });
    }

    class DownloadFileAsyncTask extends AsyncTask<Integer, Integer, Integer> {

        protected void onPreExecute() { //초기화 단계에서 사용되는 메소드
            value = 0;
            pBar.setProgress(value);
        }

        protected Integer doInBackground(Integer... params) {
            // doInBackground 메소드는 필수 메소드
            while(isCancelled() == false){
                value++;
                if(value >=100){
                    break;
                }else{
                    publishProgress(value);
                }
                try{
                    Thread.sleep(100);
                }catch(Exception e){}
            } //while of End

            return value;
        }

        protected void onProgressUpdate(Integer... values) {
            //백그라운드 작업의 진행상태를 표시하기 위해서 호출하는 메소드
            pBar.setProgress(values[0].intValue());
            textView.setText("작업 진행정도 : "+values[0].toString()+"%");
        }

        protected void onPostExecute(Integer result) {
            //백그라운 작업이 끝난후에 호출되는 메소드
            pBar.setProgress(0);
            textView.setText("작업 진행 완료");
        }

        protected void onCancelled(){
            // cancel메소드를 호출하면 자동으로 호출되는 메소드
            // 작업을 취소했을 경우에 사용되는 메소드
            pBar.setProgress(0);
            textView.setText("작업 진행 취소됨");
        }
    }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/titleText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="AsyncTask Exercise"
        android:textSize="20dp"
        android:gravity="center"
        android:textColor="@color/colorAccent"
        android:layout_margin="10dp"
        />

    <TextView
        android:id="@+id/txtView01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18dp"
        android:padding="10dp"
        android:text="Progress Status"/>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_marginTop="5dp"
        android:max="100"
        android:padding="10dp"
        />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">

        <Button
            android:id="@+id/btnStart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginTop="5dp"
            android:layout_marginRight="20dp"
            android:text="시작"
            android:textSize="18dp"/>
        <Button
            android:id="@+id/btnCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginTop="5dp"
            android:text="취소"
            android:textSize="18dp"
            />

    </LinearLayout>
</LinearLayout>



블로그 이미지

Link2Me

,