GPS 활용 동영상 강좌



권한 설정하기

GPS를 사용하기 위해서는 AndroidManifest.xml 파일에 다음과 같이 권한을 설정 부분을 추가해줍니다.

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


레이아웃 설정하기

레이아웃은 맵을 오픈하기 위한 버튼과 위도, 경도를 표시할 텍스트 뷰어, 상세 주소를 표시할 텍스트 뷰어 이렇게 총 3개의 아이템이 필요합니다. Linear 레이아웃에 상단 버튼 하나와 텍스트 뷰 2개를 가져다 놓습니다.

layout 폴더 아래에 있는 main.xml 파일에 다음과 같이 입력합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
<Button android:text="Open Map" android:id="@+id/Button01" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<TextView android:text="" android:id="@+id/TextView01" android:layout_width="fill_parent" android:layout_height="wrap_content"></TextView>
<TextView android:text="" android:id="@+id/TextView02" android:layout_width="fill_parent" android:layout_height="wrap_content"></TextView>
</LinearLayout>


엑티비티 GPS 사용하기

GPS를 사용하기 위해서는 LocationManager 타입의 멤버변수를 선언하고 onCreat 메소드에서 객체를 생성합니다. 그리고 Criteria 클래스를 사용하여 GPS 옵션을 설정합니다.
GPS 정보를 받아오기 위해서는 Provider를 생성하고 requestLocationUpdates 메소드를 사용하여 GPS 정보를 받아옵니다. 그리고 listener는 현재 액티비티로 설정해줍니다. 액티비티를 listener 를 사용하기 위해서는 액티비티에 LocationListener 인터페이스를 상속받아야 합니다. 인터페이스를 상속받아 사용하는 방법은 더 아래쪽에서 설명합니다.

//전역변수에 LocationManager 선언
private LocationManager _Location = null;

public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	//내부에서 GPS 서비스가 돌고 있는 경우에 위치 정보를 읽을수 있는 LOCATION 서비스를 가져옵니다.
    _Location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    //옵션을 설정하기 위한 객체 생성
    Criteria _Criteria = new Criteria();
    //정확도(해당사항 없음)
    _Criteria.setAccuracy(Criteria.NO_REQUIREMENT);
    //전력 소모량(해당사항 없음)
    _Criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);

    //GPS 정보를 받아올 Provider를 생성>
    String _BestProvider = _Location.getBestProvider(_Criteria, true);

    //GPS 정보를 가져옴
    //1초마다 지역정보가 변경이 될때마다 알려줌
    _Location.requestLocationUpdates(_BestProvider, 1000, 0, this);
}


LocationListener 인터페이스 상속받아 사용하기

액티비티 클래스에 LocationListener 인터페이스를 상속 받고 다음과 같은 메소드들을 오버라이딩 해줍니다.

public class Main extends Activity implements LocationListener {

	... 생략 ...

	//GPS를 읽을 수 있는 상태가 되었을때 실행됩니다.
	//requestLocationUpdates 메소드에 의해 실행 된다.
	public void onProviderEnabled(String provider) {

	}

	//위치정보가 바뀔때 마다 실행됩니다.
	public void onLocationChanged(Location location) {

	}

	//상태가 변하면 실행
	public void onStatusChanged(String provider, int status, Bundle extra) {
    	
	}

	public void onProviderDisabled(String provider) {

	}
}


GPS 정보 표시하기

GPS 위치가 변경될때마다 textview에 표시되도록 하기 위해서는 onLocationChanged 메소드에 다음과 같은 코드를 입력합니다. 우선 _TextView는 생성되어 있어야합니다.

public void onLocationChanged(Location location) {
	_TextView.setText(
String.format("위도: %f, 경도: %f, 고도: %f", location.getLatitude(), location.getLongitude(), location.getAltitude() ) ); }

GPS 위도와 경도를 가지고 상세 정보를 가져오는 메소드

private String get_GeoCode(Double Latitude, Double Longitude) {
	String _Result = "";

	//상세 주소를 가져오는 객체
	Geocoder _Geocoder = new Geocoder(this);

	try {
		//위도와 경도에 맞는 주소를 3개를 가져온다.
		Iterator<address> _Address = _Geocoder.getFromLocation(Latitude, Longitude, 3).iterator();
		if(_Address != null) {
			while(_Address.hasNext()) {
				Address namedLoc = _Address.next();
				String placeName = namedLoc.getLocality();
				String featureName = namedLoc.getFeatureName();
				String contury = namedLoc.getCountryName();
				String road = namedLoc.getThoroughfare();
				_Result += String.format("\n[%s][%s][%s][%s]", placeName, featureName, road, contury);
				int addIdx = namedLoc.getMaxAddressLineIndex();
				for(int idx = 0; idx <= addIdx; idx++ ) {
					String addLine = namedLoc.getAddressLine(idx);
					_Result += String.format("\nLine %d: %s", idx, addLine);
				}
			}
		}
		return _Result;
	} catch(IOException e) {
		return "Error";
	}
}

Map을 오픈하여 보여주는 메소드

public void do_OpenMap(double Latitude, double Longitude) {
	//URI를 전달시켜서 URI에 맞는 액티비티를 자동으로 뜨게끔 한다.
	Uri _GeoURI = Uri.parse(String.format("geo:%f, %f", Latitude, Longitude));
	//URI에 해당하는 액티비티를 보여주는 Intent 생성
	Intent _GeoMap = new Intent(Intent.ACTION_VIEW, _GeoURI);
	//현재 액티비티에 해당 인텐더를 보여줍니다.
	startActivity(_GeoMap);
}


실행 결과


참고: 안드로이드 에뮬레이터에서 GPS 사용하는 방법

전체 소스

Posted by 피곤키오
,