안드로이드 volley 질문드립니다~

조회수 607회
public class MainActivity extends AppCompatActivity {
LocationManager manager;

List<String> enabledProviders;

float bestAccuracy;
double lat;
double lng;
String data;
String stationName;
String dustTime;

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

    if (AppHelper.requestQueue == null) {
        AppHelper.requestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    manager = (LocationManager)getSystemService(LOCATION_SERVICE);
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 100);
    } else {

    }

    Button button = findViewById(R.id.re_button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getProviders();
            getLocation();
        }
    });


}

private void showToast(String message){
    Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
    toast.show();
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 100 && grantResults.length > 0) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            getProviders();
            getLocation();
        } else {
            showToast("no permission...");
        }
    }
}

private void getProviders(){
    String  result = "App providers : ";
    List<String> providers = manager.getAllProviders();
    for (String provider : providers){
        result += provider + ",";
    }

    result = "Enabled Provides : ";
    enabledProviders = manager.getProviders(true);
    for (String provider : enabledProviders){
        result += provider + ",";

    }
}

private void getLocation(){
    for (String provider : enabledProviders){
        Location location = null;
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            location = manager.getLastKnownLocation(provider);
        }
        else {
            showToast("권한 없음");
        }
        if (location != null) {
            float accurcy = location.getAccuracy();
            if (bestAccuracy == 0) {
                bestAccuracy = accurcy;
                setLocationInfo(provider, location);
            }else {
                if (accurcy<bestAccuracy){
                    bestAccuracy = accurcy;
                    setLocationInfo(provider, location);
                }
            }
        }
    }

}
private void setLocationInfo(String provider, Location location){
    if (location != null) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        TextView textView = findViewById(R.id.stationname_tv);
        Log.d("location", "data:"+lat+lng);
        String url = "http://openapi.airkorea.or.kr/openapi/services/rest/MsrstnInfoInqireSvc/getNearbyMsrstnList?tmX="+lat+"&tmY="+lng+"&pageNo=1&numOfRows=10&ServiceKey=P7D382pxAC1BmoMRsbrVGYmWh%2FvoZ4HQsAf5Z%2BsPAyWlVUpe178UHS%2BekKoLR2k%2Bo7V5B5lZV71p8fIMMBiHAQ%3D%3D&_returnType=json";
        senRequest(url);
    } else {
        showToast("location null");
    }
}

//한번만 만들면 된다.
//요청을 보내기위한 객체를 만든다
public void senRequest(String url) {
        StringRequest request = new StringRequest(
                Request.Method.GET,
                url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        stationName = processResponse(response);
                        Log.d("stationResponse", stationName);
                        TextView textView = findViewById(R.id.stationname_tv);
                        textView.setText(stationName);
                        if (stationName != null) {
                            String url1 = "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty?stationName="+stationName+"&dataTerm=month&pageNo=1&numOfRows=10&ServiceKey=P7D382pxAC1BmoMRsbrVGYmWh%2FvoZ4HQsAf5Z%2BsPAyWlVUpe178UHS%2BekKoLR2k%2Bo7V5B5lZV71p8fIMMBiHAQ%3D%3D&ver=1.3&_returnType=json";
                            dust(url1);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        String message = error.getMessage();
                        Log.d("request", message);
                    }
                }

        ){
        };
        request.setShouldCache(false);
        AppHelper.requestQueue.add(request);
    }

public String processResponse(String response){
    Gson gson = new Gson();
    StationList stationList = gson.fromJson(response, StationList.class);
    StationInfo lists = stationList.list.get(1);
    data = lists.stationName;
    Log.d("onResponse", data);
    return data;
}

public void dust(String url) {
    StringRequest request = new StringRequest(
            Request.Method.GET,
            url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    dustTime = dustResponse(response).getDataTime();
                    String pm10Value = dustResponse(response).getPm10Value();
                    TextView textView = findViewById(R.id.datatime_tv);
                    TextView textView1 = findViewById(R.id.pm10value_tv);
                    textView.setText(dustTime);
                    textView1.setText(pm10Value);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    String message = error.getMessage();
                    Log.d("request", message);
                }
            }

    ){
    };
    request.setShouldCache(false);
    AppHelper.requestQueue.add(request);
}

public DustInfo dustResponse(String response){
    Gson gson = new Gson();
    DustList dustList = gson.fromJson(response, DustList.class);
    DustInfo dustInfo = dustList.list.get(0);
    dustInfo.setDataTime(dustInfo.dataTime);
    dustInfo.setPm10Value(dustInfo.pm10Value);

    return dustInfo;
}
}

폰에서 위도와 경도를 받아와서 측정소api에서 측정소의 이름을 받아와 다시 미세먼지 api로 보냅니다. 이렇게해서 pm10value를 받아오는데 에뮬레이터에서 돌리면 에뮬레이터에 있는 GPS좌표로 잘 작동합니다. 그런데 실제 핸드폰에 연결해서 하면 에뮬이랑 똑같은 GPS가 잡힙니다... 이유가 뭘까요.. 그리고 저렇게 요청을 두번 보내도 상관 없는건가요? 혹은 다른 클래스를 생성하는 방법이 있나요?

  • (•́ ✖ •̀)
    알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)