본문 바로가기
프로그램 개발해서 돈벌기/Android

[Java] 안드로이드 Activity와 Forground Service에서 위치 값 가져오기

by ubmuhan 2023. 6. 26.
반응형

Activity에서 위치 값 가져오기

 

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 

멤버 변수로 설정

double mLatitude = 0;
double mLongitude = 0;
private FusedLocationProviderClient fusedLocationProviderClient;

 

onCreate에서 fusedLocationProviderClient 초기화

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

    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

 

위치 값 가져오기

private void getCurrentLocation() {
    try {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
        }
        fusedLocationProviderClient.getLastLocation()
                .addOnSuccessListener(this, location -> {
                    if (location != null) {
                        // 현재 위치 가져오기 성공
                        mLatitude = location.getLatitude();
                        mLongitude = location.getLongitude();
                        Log.e("Location", "Latitude: " + mLatitude + ", Longitude: " + mLongitude);
                    } else {
                        Log.e("Location", "Failed to get current location.");
                    }
                });
    } catch (Exception e) {
        Log.e("Location", "Failed to get current location.");
    }
}

 

Forground Service에서 위치 값 가져오기

Activity에서 사용한 위 방법으로는 위치 값을 가져올 수 없습니다. 서비스에서 getLastLocation으로 호출을 해도 위치 값을 항상 0 입니다.

그래서 LocationRequest를 이용해서 위치 값을 가져옵니다.

 

AndroidManifest.xml 내 권한은 위와 같습니다.

 

멤버 변수로 설정

private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback locationCallback;

 

onCreate에서 LocationCallback을 이용해서 위치 값 가져오기

@Override
public void onCreate() {
    super.onCreate();
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    // 위치 업데이트를 위한 LocationRequest 생성
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    //locationRequest.setInterval(mnTimer);
    locationRequest.setInterval(SJSingtonData.getInstance().nTime);

    // 위치 업데이트를 처리하는 LocationCallback 생성
    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                // 위치 값을 가져와서 원하는 작업을 수행합니다.
                mLatitude = location.getLatitude();
                mLongitude = location.getLongitude();
                // 원하는 작업을 수행하세요.
                Log.e("Location2", "Latitude: " + mLatitude + ", Longitude: " + mLongitude);
            }
        }
    };

    // 위치 업데이트 시작
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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.
    } else {
        fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
    }

 

미국식
[loʊ│keɪʃn]
영국식
[ləʊ│keɪʃn]
1. (…이 일어나는·존재하는) 장소[곳/위치]
2. (영화의) 야외 촬영지[로케이션]
3. …의 위치[소재] 찾기[추적]
 
 
 
반응형

댓글