Web & Mobile/Android

[Android] AsyncTask ProgressDialog 멈춤 현상

byunghyun23 2024. 3. 9. 20:49

AsyncTask으로 작업을 비동기로 수행할 때, ProgressDialog로 현재 작업이 진행중임을 화면에 나타낼 수 있습니다.

 

public class GetTask extends AsyncTask<String, Void, String> {
    private Context context;
    private ProgressDialog progressDialog;

    public GetTask(Context context) {
        this.context = context;
        this.progressDialog = new ProgressDialog(context);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog.setMessage("작업 중...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String URL = params[0];

        try {
            URL url = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 설정 가능한 다양한 요청 속성들을 설정 (예: 요청 메소드, 헤더 등)
            connection.setRequestMethod("GET");

            // 응답 코드 확인
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 응답 데이터 읽기
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                return response.toString();
            } else {
                return "[Error] " + responseCode;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "[Error] " + e.getMessage();
        }

    }

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

        progressDialog.dismiss();
    }
}

 

String URL = "localhost:8080/home";
String response = new GetTask(MainActivity.this).execute(URL).get();
// .. 이후 response를 파싱하여 UI 업데이트

 

하지만 MainActivity에서 위와 같이 호출할 경우, doInBackGround() 작업이 모두 끝난 후 리턴 값을 response에 저장하게 됩니다. 이럴 경우 UI 작업을 차단하여 doInBackGround() 작업이 모두 끝난 후 ProgressDialog가 화면에 아주 잠깐 보이고 바로 사라집니다. (doInBackGround()의 리턴 값을 기다리기때문)

 

따라서 execute().get() 대신에 아래와 같이 execute()만 실행하면서 doInBackGround()의 리턴값을 입력으로 받아 호출되는 onPostExecute()를 오버라이드해서 UI 작업을 작성해주면 됩니다.

 

String URL = "localhost:8080/home";

new GetTask(MainActivity.this) {
    @Override
    protected void onPostExecute(String response) {
        super.onPostExecute(response);

       	// .. 이후 response를 파싱하여 UI 업데이트
    }
}.execute(URL);

 

 

'Web & Mobile > Android' 카테고리의 다른 글

[Android] REST API 호출  (0) 2024.03.08
[Android] 기존 프로젝트 이름 변경하기  (0) 2022.01.21