Android 현재 위치 가져오기

pass·2023년 7월 20일
0

Android

목록 보기
19/36

🔥 Android 에서 현재 위치의 위도와 경도 가져오기


🌈 배경

이번 android 프로젝트에서 일출 일몰 API 를 사용하여 오늘 날짜의 일출 시간과 일몰 시간을 가져오는 과정이 필요하였다.
공공데이터 포털에서 일출, 일몰 시간을 제공해주는 API 를 발견하여 사용하기로 하였다.
공공데이터포털 : https://www.data.go.kr/data/15012688/openapi.do

요청 파라미터로 현재 위도와 경도값을 같이 보내주어야 하기 때문에 Android 에서 GPS를 통해
현재 위치 위도와 경도를 가져오는 작업을 수행하였다.


참고 : 안드로이드 공식 문서

https://developer.android.com/training/location/permissions?hl=ko



✔ Manifest.xml

<manifest ... >
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>
  • Manifest 에 권한 추가
  • ACCESS_COARSE_LOCATION
    • 대략적인 위치
    • 오차범위 약 3제곱킬러미터 이내
  • ACCESS_FINE_LOCATION
    • 최대한 정확한 위치
    • 오차범위 약 50미터 이내



✔ MainActivity.java

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

    // check permission
    locationPermissionRequest.launch(new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    });
}

ActivityResultLauncher<String[]> locationPermissionRequest =
    registerForActivityResult(new ActivityResultContracts
        .RequestMultiplePermissions(), result -> {
            Boolean fineLocationGranted = result.getOrDefault(
                    Manifest.permission.ACCESS_FINE_LOCATION, false);
            Boolean coarseLocationGranted = result.getOrDefault(
                    Manifest.permission.ACCESS_COARSE_LOCATION,false);
            if (fineLocationGranted != null && fineLocationGranted) {
                // Precise location access granted.
            } else if (coarseLocationGranted != null && coarseLocationGranted) {
                // Only approximate location access granted.
            } else {
                // No location access granted.
            }
        }
    );
  • Activity가 화면에 보이는 상태에서 권한을 확인할 수 있도록 onResume 에서 권한 확인을 수행하였다.



✔ 사용

LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// 마지막 위치 받아오기
Location current = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

// 위도, 경도 (순서대로)
String longtitude = String.valueOf(current.getLongitude());
String latitude = String.valueOf(current.getLatitude());
  • 이렇게 변수와 함수를 사용하여 위도, 경도 값을 가져올 수 있었다.
  • 주의할 점은 GPS_PROVIDER 는 GPS를 사용하는 것이기 때문에 야외에서만 사용이 가능하다.



profile
안드로이드 개발자 지망생

1개의 댓글

comment-user-thumbnail
2023년 7월 20일

잘 봤습니다. 좋은 글 감사합니다.

답글 달기