프로그래밍 방식으로 안드로이드에서 현재 GPS 정보를 가져오는 방법
조회수 2198회
1 답변
-
현재 위치를 GPS 좌표값으로 받아오는 방식을 순차적으로 설명해놓은 예제 앱을 소개해드립니다.
전체 소스 코드는 Get Current Location coordinates , City name - in Android에서 볼 수 있습니다.
작동 방식 :
가장 먼저 해야할 일은 manifest 파일에 아래 권한을 등록하는 겁니다 :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
그 다음,
LocationManager
인스턴스를 생성해주고 :LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
GPS가 활성화되었는지 확인한 뒤,
LocationListener
를 구현하여 좌표를 받아옵니다 :LocationListener locationListener = new MyLocationListener(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
아래는
LocationListener
에 대한 샘플 코드입니다.
/*---------- Listener class to get coordinates ------------- */ private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { editLocation.setText(""); pb.setVisibility(View.INVISIBLE); Toast.makeText( getBaseContext(), "Location changed: Lat: " + loc.getLatitude() + " Lng: " + loc.getLongitude(), Toast.LENGTH_SHORT).show(); String longitude = "Longitude: " + loc.getLongitude(); Log.v(TAG, longitude); String latitude = "Latitude: " + loc.getLatitude(); Log.v(TAG, latitude); /*------- To get city name from coordinates -------- */ String cityName = null; Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault()); List<Address> addresses; try { addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1); if (addresses.size() > 0) { System.out.println(addresses.get(0).getLocality()); cityName = addresses.get(0).getLocality(); } } catch (IOException e) { e.printStackTrace(); } String s = longitude + "\n" + latitude + "\n\nMy Current City is: " + cityName; editLocation.setText(s); } @Override public void onProviderDisabled(String provider) {} @Override public void onProviderEnabled(String provider) {} @Override public void onStatusChanged(String provider, int status, Bundle extras) {} }
댓글 입력