본문 바로가기

Android/GPS Intro 01

GPS Introduction 01, Android

Android 에서 GPS 응용 예제

Android 모바일 기기에 내장된 GPS 로부터 위도, 경도 정보를 받아서 화면에 출력하는 예
GPS로부터 위치정보를 수신하려면 LocationManager가 필요하고 LocationManager가 수신한 위치정보에 변화가 있는 경우에는 LocationListener 인터페이스의 onLocationChanged()를 이용하여 처리할 작업을 정의할 수 있다.

Eclipse > New > Android Project

AndroidManifest.xml
기본으로 생성된 내용에 적색으로 표시한 요소를 추가함

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.ojtit.android.gps.demo"
      android:versionCode="1"
      android:versionName="1.0">
     
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
       
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".GPSActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="7" />

</manifest>




main.xml
기본으로 생성된 내용에 적색부분의 속성을 추가함
TetxtView에 GPS의 위도, 경도정보를 출력하려고 함

<?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"
    >
<TextView
    android:id="@+id/textview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>



GPSActivity.java
LocationListener를 LocationManager에 등록하여 위치정보가 변경된 경우에 처리할 내용을 정의한다.

package com.ojtit.android.gps.demo;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class GPSActivity extends Activity
{
    private LocationManager lm;
    private LocationListener locationListener;
   
    private TextView textView; /*경도, 위도 정보를 출력할 뷰 */
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        textView = (TextView)findViewById(R.id.textview);
       
        //---use the LocationManager class to obtain GPS locations---
        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
       
        locationListener = new MyLocationListener();
       
        lm.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            0,
            0,
            locationListener);       
    }
   
    // 내부 클래스로 구현한 LocationListener
    private class MyLocationListener implements LocationListener
    {
        @Override
        public void onLocationChanged(Location loc) {
            if (loc != null) {
             /*Toast에 의해서 화면하단에 위도, 경도가 출력됨 */
                Toast.makeText(getBaseContext(),
                    "Location changed : Lat: " + loc.getLatitude() +
                    " Lng: " + loc.getLongitude(),
                    Toast.LENGTH_SHORT ).show();
                /* 화면의 상단에 위치한 TextView에 위도, 경도를 출력함*/
                textView.setText("위도:"+loc.getLatitude()+", 경도:"+loc.getLongitude());
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status,
            Bundle extras) {
            // TODO Auto-generated method stub
        }
    }       
    // 내부 클래스 끝
}




R.java
편집할 필요가 없으며 시스템에 의해 자동으로 리소스가 등록됨

/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.ojtit.android.gps.demo;

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class id {
        public static final int textview=0x7f050000;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f040001;
        public static final int hello=0x7f040000;
    }
}



Run As > Android Application
프로그램을 실행하면 오류 없이 실행되지만 위도, 경도 정보가 표시되지 않고 있다. 그 이유는 GPS로부터 위치정보가 전달되지 않기 때문이다. 실제 안드로이드 폰이고 GPS가 내장되어 있다면 이런 현상은 없겠지만 에뮬레이터에는 GPS가 없기 때문에 당연한 결과라고 할 수 있다. 그러나 에뮬레이터에서도 GPS프로그램을 테스트할 수는 있어야 하므로 방법이 제공되고 있으므로 아래에서 그 방법을 알아 보고자 한다.

사용자 삽입 이미지

Android SDK에서는 DDMS(Dalvik Debug Monitor Service)를 제공하는데, DDMS 퍼스펙티브를 이용하면 매우 쉽게 GPS위치정보를 에뮬레이터로 전달하여 실제 GPS에서 정보가 전달되는 효과를 흉내낼 수가 있다. GPS정보를 에뮬레이터로 전달하는 방법에는 3가지가 있다.

1. 수동으로 버튼을 클릭할 때마다 한번씩 위치정보를 전달하는 방법
  DDMS 퍼스펙티브 > Emulator Control > Location Controls > Manual 선택
 위도, 경도를 입력 > Send 버튼클릭,  버튼을 클릭할 때마다 한번씩 위치정보(위도/경도)가 에뮬레이터로 전달됨
  http://maps.google.com사이트에서 지도상의 위도/경도 정보를 확인하는 방법은 여기를 참조하세요.

2. GPX (GPS Exchange Format) : 위치정보를 저장한 XML 파일을 로드하여 일정기간 동안 위치정보를 지속적으로 전달하는 방법, GPX파일을 로드한 후에 PLAY 버튼을 누르면 일련의 위치정보가 에뮬레이터로 전달된다. 파일 작성법 및 GPX파일 사용법은 여기를 참조하세요.

3. KML (Keyhole Markup Language) : GPX와 같이 kml 파일을 로드하여 PLAY버튼을 누르면 일련의 위치정보가 에뮬레이터로 전달된다.


위의 3가지 방법을 사용하기 위해서는 먼저 Eclipse의 Persfective 부터 변경해야 한다. DDMS 퍼스펙티브를 사용하여 에뮬레이터에 위치정보를 전달하기 위해서는 먼저 위와 같이 에뮬레이터가 실행된 상태이어야 한다. 위치정보를 받을 수 있는 에뮬레이터가 먼저 실행된 상태에서 에뮬레이터로 GPS 위치정보를 전달해야 하므로 당연한 이야기이다.

에뮬레이터가 실행된 상태에서 다음과 같이 DDMS 퍼스펙티브로 전환한다.

사용자 삽입 이미지



사용자 삽입 이미지


다음과 같이 DDMS 퍼스펙티브로 설정된다
사용자 삽입 이미지


아래의 그림과 같이 'Devices' 패널에서 'emulator-5554를 선택하고, Location ControlsManual탭을 선택한다.

사용자 삽입 이미지

위의 그림에서 Send 버튼을 누를 때마다 입력한 위도, 경도 정보가 에뮬레이터로 전달되어 TextView와 Toast에 의해 출력될 것이다. 아래 그림 참조

사용자 삽입 이미지