본문 바로가기
안드로이드

[Android] GPS 위치정보 가져오기

by 코딩히어로 2023. 1. 3.
728x90

1


실질적으로 Android App에서 GPS를 통한 위치정보는 스토어에 올릴 수가 없습니다

특수한 목적과 법적인 제한사항이 있다보니 대한민국의 경우에는 굉장히 민감해서

예전 프로젝트에서 GPS 연동을 통한 트래킹 어플을 개발했지만 결국 출시하지 못했던 경험이 있습니다

하지만 개인적인 목적이나 출시를 하지 않는다면 GPS정보는 굉장히 유용하게

사용될 수 있는데 이번 포스팅에서는 해당 정보를 읽어오는 방법에 대해 알아보겠습니다

 

GPS 정보를 읽어오기 위해서는 ACCESS_FINE_LOCATION에 대한 유저 권한이 필요합니다.

private String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
private boolean mLocationPermissionApproved = false;

private boolean checkPermission() {
    int result;
    List<String> listPermission = new ArrayList<>();
    for (String p : permission) {
        result = ContextCompat.checkSelfPermission(LoginActivity.this, p);
        if (result != PackageManager.PERMISSION_GRANTED) {
            listPermission.add(p);
        }
    }
    if (!listPermission.isEmpty()) {
        ActivityCompat.requestPermissions(LoginActivity.this, listPermission.toArray(new String[listPermission.size()]), 0);
        return false;
    }
    return true;
}

먼저 유저에게 권한을 확인하고 요청하는 checkPermission 함수를 만들어줍니다

App이 실행되면 해당 함수를 먼저 호출하여 권한을 획득해야 합니다

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

다음으로는 GPS 정보를 가져오기 위한 locationManager를 선언합니다

Android에서는 GPS 정보를 locationManager의 GPS와 NETWORK를 이용해서 읽어옵니다

이 중에서 NETWORK는 보조수단으로 사용하셔야 합니다.

double latitude=0;
double longitude=0;

if (isGPSEnable && isNetworkEnable) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if(location!=null){
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Log.i("디버깅","값확인좀 = "+latitude+"/"+longitude);
    }else{
        Location locations = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if(locations!=null){
            latitude = locations.getLatitude();
            longitude = locations.getLongitude();
            Log.i("디버깅","값확인좀 = "+latitude+"/"+longitude);
        }
    }
}

GPS 정보는 latitude와 longitude로 구성되어 있습니다

이 두가지 정보를 가지고 google map에 입력해보면 해당 위치가 검색됩니다.

먼저 locationManager의 GPS를 통해 정보를 읽어오는데 해당 location이 null일 경우가 있습니다

이럴 경우 위에서 말한 것과 같이 보조수단인 location의 NETWORK 정보를 통해서 위치를 읽어오면 됩니다.

728x90
반응형

댓글