안드로이드에서 위치정보를 출력하는 방법이다.
===================================================================================================================
public class GPS {
private static final String TAG = "GPS ";
private Context mContext = null;
private LocationManager mLocationManager = null;
public double dbLat, dbLng;
public GPS(Context context){
this.mContext = context;
if(this.mContext != null){
// 1. LocationManager 객체 생성
this.mLocationManager = (LocationManager) this.mContext.getSystemService(Context.LOCATION_SERVICE);
}
}
// 2. LocationListener에 해당 프로바이더 등록(GPS, NETWORK)
public LocationListener [] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
// 3. LocationListener 리스너 설정
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
boolean mValid = false;
String mProvider;
public LocationListener(String provider){
mProvider = provider;
mLastLocation = new Location(mProvider);
}
// 4 . 현재 자신의 위치가 바뀔 때마다 업데이트 되는 내용. (난 단순히 위,경도를 출력)
//Called when the location has changed.
public void onLocationChanged(Location newLocation){
if (newLocation.getLatitude() == 0.0 && newLocation.getLongitude() == 0.0){
// Hack to filter out 0.0,0.0 locations
// MainActivity(Main Thread)에서 Context를 넘겨 받았으니, 실행이된다.
Toast.makeText(mContext, "Try again", Toast.LENGTH_SHORT).show();
return;
}
if (newLocation != null){
///if(newLocation.getTime() == 0) newLocation.setTime(System.currentTimeMillis());
newLocation.setTime(System.currentTimeMillis());
Toast.makeText(mContext, "위도:"+ String.valueOf(newLocation.getLatitude()) +
" 경도: " + String.valueOf(newLocation.getLongitude()),
Toast.LENGTH_SHORT).show();
if(newLocation.getLatitude() != 0.0 && newLocation.getLongitude() != 0.0 ){
strNowLocationLatLngInfo = SC.getTime() + "GPS Lat:" +
String.valueOf(newLocation.getLatitude()) + " Lng:" +
String.valueOf(newLocation.getLongitude());
//MainActivity.dbLatitude = newLocation.getLatitude();
dbLat = newLocation.getLatitude();
dbLng = newLocation.getLongitude();
}else{
strNowLocationLatLngInfo = "Not available";
Toast.makeText(mContext, strNowLocationLatLngInfo,
Toast.LENGTH_SHORT).show();
}
if(Config.DEBUG){
Log.i(TAG, "onLocationChanged in loc mgnr");
}
}
mLastLocation.set(newLocation);
mValid = true;
}
// Called when the provider is ㄷabled by the user.
public void onProviderEnabled(String provider) {
}
// Called when the provider is disabled by the user.
public void onProviderDisabled(String provider){
mValid = false;
}
// Called when the provider status changes.
public void onStatusChanged(String provider, int status, Bundle extras){
if (status == LocationProvider.OUT_OF_SERVICE){
mValid = false;
}
}
/**
* @brief 현재 위치가 유효한지 확인
* @return 현재 위치
*/
public Location current(){
return mValid ? mLastLocation : null;
}
};
// 5. 위치 추적
/**
* @ brief 위치 검색 시작
*/
public void startLocationReceiving(){
if (this.mLocationManager != null){
try{
// 5-1. 지정된 provider, 시간, 거리마다 해당 listener에 request됨.(결국, 이 메소드로 위치정보얻기가 실행됨)
this.mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
0,
0F,
this.mLocationListeners[1] );
}catch (java.lang.SecurityException ex){
if(Config.DEBUG){
Log.e(TAG, "SecurityException " + ex.getMessage());
}
}catch (IllegalArgumentException ex){
//Log.e(TAG, "provider does not exist " + ex.getMessage());
}
try{
this.mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0F,
this.mLocationListeners[0]);
}catch (java.lang.SecurityException ex){
if(Config.DEBUG){
Log.e(TAG, "SecurityException " + ex.getMessage());
}
}catch (IllegalArgumentException ex){
//Log.e(TAG, "provider does not exist " + ex.getMessage());
}
}
}
// 6. 위치 추적 종료
/**
* @ brief 위치 검색 종료
*/
public void stopLocationReceiving() {
if (this.mLocationManager != null) {
for (int i = 0; i < this.mLocationListeners.length; i++){
try{
this.mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
// ok
}
}
}
}
// 7. 현재 위치의 Location정보 얻기
/**
* @ brief 현재 위치 정보 검색
*/
public Location getCurrentLocation() {
Location l = null;
// go in best to worst order
for (int i = 0; i < this.mLocationListeners.length; i++) {
l = this.mLocationListeners[i].current();
if (l != null){
break;
}
}
return l;
}
}
===================================================================================================================
메인 스레드(보통 안드로이드에서 MainActivity)에서 불러오는 방법은 간단하다.
1. 객체 생성하고
2. 스타트 시키고
3. 앱 종료시, 혹은 기타 상황에 스탑.
이정도는 알것이라 생각하고 생략. 모르면 기초부터 배우자.
혹시 이상한 부분이나 수정되어야 하는 부분이있으면 댓글 남겨줘
'6. With IT > 6.1 Android' 카테고리의 다른 글
안드로이드 어플리케이션 기초적인 내용들 (0) | 2013.10.17 |
---|---|
apk만들기 (0) | 2013.03.05 |
안드로이드 종합 (0) | 2013.02.18 |
이클립스 플러그인(svn)설치 (0) | 2013.02.06 |
파일전송(웹 서버 : 아파치서버) (3) | 2013.02.05 |