마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

NetworkOnMainThreadException 에러

0 추천
package com.example.sdna.pushtotts2;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

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

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RpmMonitorActivity extends AppCompatActivity {
    String responseStr = null;
    String rpmStr;
    TextView rpmTextView;
    ImageView RpmMonitor_rpmpin;

    Button rpmStartButton;
    Boolean isThreadRunning = false;
    HttpGet hg;

    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {   // Message id 가 0 이면

            }
        }
    };

    /*
    가장먼저 OnCreate() -> OnStart(), 인터넷연결을 위한 OnResum()이 실행 됩니다.
    그리고, 뒤로가기버튼을 누르게 되면 OnPause() -> OnStop() -> OnDestroy() 순서로 진행됩니다.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rpm_monitor);
        rpmTextView = (TextView) findViewById(R.id.rpmTextView);
        rpmStartButton = (Button) findViewById(R.id.rpmStartButton);
        RpmMonitor_rpmpin = (ImageView) findViewById(R.id.RpmMonitor_rpmpin);

        rpmStartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isThreadRunning == false) {
                    hg= new HttpGet();
                    hg.running = true;
                    hg.run();
                    isThreadRunning = true;
                } else {
                    hg.running = false;
                    isThreadRunning = false;
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isThreadRunning == true) {
            isThreadRunning = false;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private class HttpGet extends Thread{
        boolean running=true;
        HttpOperation HO;
        @Override
        public void run() {
            if(running) {
                HttpUrl url = new HttpUrl.Builder()
                        .scheme("http") //http
                        .host("1cccccc9")
                        .port(3000)
                        //.addPathSegment("pathSegment")//adds "/pathSegment" at the end of hostname
                        .addPathSegment("mysql_test")
                        //.addQueryParameter("param1", "value1") //add query parameters to the URL
                        //.addEncodedQueryParameter("encodedName", "encodedValue")//add encoded query parameters to the URL
                        .build();

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    responseStr = response.body().string();
                    JSONArray jsonOutput = null;
                    try {
                        jsonOutput = new JSONArray(responseStr);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    JSONObject tem = jsonOutput.getJSONObject(0);
                    rpmStr = tem.getString("rpm");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                HO = new HttpOperation();
                HO.execute();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        private class HttpOperation extends AsyncTask<String, Void, String> {
            boolean runnig = true;
            int beforeDgreeRpm = 0;

            @Override
            protected String doInBackground(String... params) {
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                rpmTextView.setText(rpmStr+"00/s");

                //rpm은 10~70의 값이 들어온다
                //0==0 / 90==180
                int rpmint = Integer.parseInt(rpmStr);
                rpmint = (rpmint * 2)+25;
                RotateAnimation ani1 = new RotateAnimation(beforeDgreeRpm, rpmint, RotateAnimation.RELATIVE_TO_SELF, 0.83f, RotateAnimation.RELATIVE_TO_SELF, 0.33f);
                ani1.setFillAfter(true);
                ani1.setDuration(1000);
                ani1.setRepeatCount(0);
                RpmMonitor_rpmpin.setAnimation(ani1);
                RpmMonitor_rpmpin.startAnimation(ani1);
                beforeDgreeRpm = rpmint;
            }

            @Override
            protected void onPreExecute() {
            }

            @Override
            protected void onProgressUpdate(Void... values) {
            }

            @Override
            protected void onCancelled() {
                runnig = false;
            }
        }
    }
}

 

위와같이 

hg= new HttpGet();
hg.running = true;
hg.run();

을 통해 새 스레드를 만들어서 http통신을 진행 했는데

Response response = client.newCall(request).execute();

부분에서  NetworkOnMainThreadException 에러가 발생합니다

new를 통해 새로 만든 thread도 메인스레드로 취급하는건가요??

어떻게 수정해야 할까요

신입 (570 포인트) 님이 2016년 12월 5일 질문

1개의 답변

0 추천

Thread의 시작은 hg.run(); 이 아니라 start 입니다. 메소드를 잘 못 호출 하신 듯 합니다.

익명사용자 님이 2016년 12월 5일 답변
...