티스토리 뷰

안드로이드에서는 아래 제약 조건이 존재한다. 

1. Main Thread에서 네트워크 호출 금지

2. 작업 Thread에서 Main UI 접근 금지

3. Main Thread와 작업 Thread 간 데이터 전달에 Handler 사용

 

위 3가지 조건을 만족시키기 위해 코드를 작성하면 소스코드가 지저분해질 수 있는데, 아래와 같이 정리하면 Activity에서 소스코드를 단순화할 수 있게 된다.

 

 

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

        HttpHelper httpHelper = new HttpHelper();
        httpHelper.setReceiver(new Receiver() {
            @Override
            public void onResponse(int resCode, JSONObject res) {
                Log.d(TAG, "resCode: " + resCode + ", res: " + res);
                txv.setText("JSON: " + res);
            }
        });

        txv = findViewById(R.id.txv);

        Button btn = findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Click!", Toast.LENGTH_SHORT).show();

                Map<String, String> req = new HashMap<String, String>();
                req.put("option", "01012341234");
                httpHelper.doGet(req);
            }
        });
    }

 

package org.devlion.util.cmn;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class HttpHelper{

    final String TAG = "CATCH_CALL";
    public String CALL_SEVER_URL = "http://yorsild.dothome.co.kr/call.php";
    public int TIME_OUT = 3000;
    private Receiver receiver;

    public void setReceiver(Receiver receiver){
        this.receiver = receiver;
    }

    // Call back 핸들러. Http 응답을 Main Thread에게 전달한다.
    Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            int resCode = msg.arg1;
            JSONObject resJson = (JSONObject)msg.obj;
            receiver.onResponse(resCode, resJson);
        }
    };

    // Get URL 파라매터 세팅
    public void doGet(Map<String, String> params){
        Log.d(TAG, "doGet()");

        HttpService hs = new HttpService();
        hs.setParams(params);
        hs.start();
    }

    // 비동기 호출
    class HttpService extends Thread {

        Map<String, String> paramMap;

        void setParams(Map<String, String> paramMap){
            this.paramMap = paramMap;
        }

        @Override
        public void run() {

            HttpURLConnection conn = null;
            int resCode = 0;
            String res = "";
            String urlPrams = "";

            try {

                // URL GET 파라매터 세팅
                if(paramMap != null){
                    for(String key : paramMap.keySet()){

                        if(urlPrams.isEmpty()){
                            urlPrams += "?";
                        }else{
                            urlPrams += "&";
                        }

                        urlPrams += key;
                        urlPrams += "=";
                        urlPrams += paramMap.get(key);
                    }
                    Log.d(TAG, "Set url params: " + urlPrams);
                }

                // URL GET 호출
                Log.d(TAG, "URL: " + CALL_SEVER_URL + urlPrams);
                URL url = new URL(CALL_SEVER_URL + urlPrams);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Cache-Control", "no-cache");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Accept", "application/json");
                conn.setConnectTimeout(TIME_OUT);
                conn.setReadTimeout(TIME_OUT);
                conn.setDoOutput(true);
                conn.setDoInput(true);

                resCode = conn.getResponseCode();
                if (resCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line;
                    StringBuffer response = new StringBuffer();
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                        response.append('\r');
                    }
                    reader.close();
                    res = response.toString();
                }

                Message msg = handler.obtainMessage();

                msg.obj = new JSONObject(res);
                msg.arg1 = resCode;
                handler.sendMessage(msg);

                conn.disconnect();

            } catch (MalformedURLException e) {
                resCode = -1;
            } catch (IOException e) {
                resCode = -2;
            } catch (JSONException e) {
                resCode = -3;
            } finally {

                if(conn != null){
                    conn.disconnect();
                }
            }

            // 결과값 Message에 담아서 반납
            Message msg = handler.obtainMessage();

            JSONObject responseJSON = null;
            try {
                responseJSON = new JSONObject(res);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            msg.obj = responseJSON;
            msg.arg1 = resCode;
            handler.sendMessage(msg);

            Log.d(TAG, "-done-");
        }
    }
}

 

package org.devlion.util.cmn;

import org.json.JSONObject;

public interface Receiver {
    void onResponse(int resCode, JSONObject res);
}

예전 작성글:  https://priv.tistory.com/38

 

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함