728x90

본 내용은 강의 수강 내용과 인터넷 검색해서 보강한 자료를 기록해둔다.

AsyncTask 는 Thread 보다 자주 사용하며, MySQL(PHP) 서버와의 통신에서도 사용한다.

import 추가는 Alt + Enter 를 누르라고 팝업 알림창이 나온다. 그러면 눌러주면 된다.

Android Studio 는 오프라인 강의를 들었는데, 단축키 기능이 너무 편리하다.

XML 코드 작성시에도 기본적인 것부터 작성할 수 있게 하고 명령어를 일부 넣어주면 자동으로 팝업되면서 자동완성 기능을 편하게 완성시킨다.


package com.tistory.link2me.app10;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button btn_alert;
    Button btn_custom;
    Button btn_progress;
    TextView txt;
    ProgressDialog progressDialog;

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

        btn_alert = (Button) findViewById(R.id.btn01);
        btn_custom = (Button) findViewById(R.id.btn02);
        btn_progress = (Button) findViewById(R.id.btn03);
        txt = (TextView) findViewById(R.id.tv01);

        btn_alert.setOnClickListener(listener);
        btn_custom.setOnClickListener(listener);
        btn_progress.setOnClickListener(listener);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn01:
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("2017 프로야구 우승후보")
                            .setMessage("두산 베어스")
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getBaseContext(), "OK", Toast.LENGTH_LONG).show();
                                    txt.setText("두산 베어즈");
                                }
                            })
                            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getBaseContext(), "NO", Toast.LENGTH_LONG).show();
                                    txt.setText("LG 트윈스");
                                }
                            })
                            .show();
                    break;

                case R.id.btn02:
                    LinearLayout linearLayout = (LinearLayout) View.inflate(MainActivity.this, R.layout.custom, null);
                    final EditText editText = (EditText) linearLayout.findViewById(R.id.et01);

                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("2017 프로야구 우승 후보")
                            .setView(linearLayout)
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getBaseContext(), "OK", Toast.LENGTH_LONG).show();
                                    String winner = editText.getText().toString();
                                    txt.setText(winner);
                                }
                            })
                            .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(MainActivity.this, "CANCEL", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .show();
                    break;

                case R.id.btn03:
                    DownloadTask task = new DownloadTask(MainActivity.this);
                    task.execute(100);
                    break;
            }
        }
    };

    private class DownloadTask extends AsyncTask<Integer, String, Integer> {

        ProgressDialog progressDialog;
        private Context mContext;

        public DownloadTask(Context context){
            mContext =context;
        }

        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setIcon(android.R.drawable.ic_dialog_info);
            progressDialog.setTitle("Download");
            progressDialog.setMessage("다운로드 중...");
            progressDialog.show(); // show dialog

            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(Integer... params) {
            //doInBackground 함수는 excute() 실행시  실행됨
            final int taskCnt = params[0]; // 최대 몇인지 설정하는 변수
            publishProgress("max", Integer.toString(taskCnt));
            try {
                for (int i = 0; i < taskCnt; i++) {
                    publishProgress("progress", Integer.toString(i), "번호 " + Integer.toString(i) + "번 수행중");
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return taskCnt; // onPostExecute()함수의 인수가 됨
        }

        @Override
        protected void onProgressUpdate(String... progress) {
            //onProgressUpdate() 함수는 publishProgress() 함수로 넘겨준 데이터들을 받아옴
            if (progress[0].equals("progress")) {
                progressDialog.setProgress(Integer.parseInt(progress[1]));
                progressDialog.setMessage(progress[2]);
            }
            else if (progress[0].equals("max")) {
                progressDialog.setMax(Integer.parseInt(progress[1]));
            }
        }

        @Override
        protected void onPostExecute(Integer result) {
            //onPostExecute() 함수는 doInBackground() 함수가 종료되면 실행됨
            progressDialog.dismiss();
            super.onPostExecute(result);
        }
    }
}


첨부한 파일은 Android Studio 에서 프로젝트 생성하고 첨부한 파일을 참조해서 작성하면 도움이 된다.

app_main.zip



728x90
블로그 이미지

Link2Me

,