Android Story

[ Android ] GPS 구하기

WhiteDuck 2016. 11. 23. 11:26


GPS 위도, 경도 구하기



Android 에서 위도 경도를 구하는데에 있어서 안드로이드 6.0 이전에서는 아래의 참조만으로도 가능하다.

그러나 6.0  이후에서는 GPSLocation를 호출할 때마다 사용자에게 퍼미션을 요구하도록하여야 한다. 이는 안드로이드 측에서 처음에 과다한 퍼미션을 묻지 않게 하기 위해서 이러한 방향을 제시한 것으로 보인다.


우선 위치를 얻기 위해 기본적으로 Manifest에 권한을 추가해 준다.

AndroidManifest.xml

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


다음은 액티비티에서 위치를 수신하기 위한 메소드를 추가한다.

/**
* 사용자의 위치를 수신
*/
private Location getMyLocation() {
Location currentLocation = null;
// Register the listener with the Location Manager to receive location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 사용자 권한 요청
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MInteger.REQUEST_CODE_LOCATION);
}
else {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

// 수동으로 위치 구하기
String locationProvider = LocationManager.GPS_PROVIDER;
currentLocation = locationManager.getLastKnownLocation(locationProvider);
if (currentLocation != null) {
double lng = currentLocation.getLongitude();
double lat = currentLocation.getLatitude();
Log.d("Main", "longtitude=" + lng + ", latitude=" + lat);
}
}
return currentLocation;
}


이에 앞서서 locationManager와 locationListener를 정의해주어야하는데, 

LocationManager는 디바이스의 위치를 가져오는데 사용하는 매니저이고,

LocationListener는 위치가 변할때 마다 또는 상태가 변할 때마다 위치를 가져오는 리스너이다.


// 사용자 위치 수신기
private LocationManager locationManager;
private LocationListener locationListener;


다음은 위의 매니저와 리스너를 설정하는 부분


/**
* GPS 를 받기 위한 매니저와 리스너 설정
*/
private void settingGPS() {
// Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
// TODO 위도, 경도로 하고 싶은 것
}

public void onStatusChanged(String provider, int status, Bundle extras) {
}

public void onProviderEnabled(String provider) {
}

public void onProviderDisabled(String provider) {
}
};
}


이제 onCreate에서 settingGPS, getMyLocation 순서대로 기입한다.


// 사용자의 위치 수신을 위한 세팅 //
settingGPS();

// 사용자의 현재 위치 //
Location userLocation = getMyLocation();

if( userLocation != null ) {
// TODO 위치를 처음 얻어왔을 때 하고 싶은 것
double latitude = userLocation.getLatitude();
double longitude = userLocation.getLongitude();
}


마지막으로 위에서 사용자 권한 요청을 했을 경우 처리하는 것이 있어야 한다.

/**
* GPS 권한 응답에 따른 처리
* @param requestCode
* @param permissions
* @param grantResults
*/
boolean canReadLocation = false;
public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) {
if (requestCode == MInteger.REQUEST_CODE_LOCATION) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// success!
Location userLocation = getMyLocation();
if( userLocation != null ) {
// 다음 데이터 //
String lang = MString.getLangFromSystemLang(getApplicationContext());
// todo 사용자의 현재 위치 구하기
double latitude = userLocation.getLatitude();
double longitude = userLocation.getLongitude();
}
canReadLocation = true;
} else {
// Permission was denied or request was cancelled
canReadLocation = false;
}
}
}



참조 : http://www.fun25.co.kr/blog/android-simple-gps-example

반응형