|
안드로이드(Android) GPS LocationListener 이용해서 도시이름 가져오기 |
|
환경 : Eclipse Mars, Android 4.2.2 |
이번예제는 LocationListener 이용해서 GPS 정보를 얻은후 도시 이름을 가져오는 것입니다. 도시 이름은 Geocoder 를 이용해서 가져옵니다. LocationListener 을 셋팅하게 되면 방위가 바뀔 때 마다 이벤트를 주게 되는데 그 정보로 정보를 찾는 방식입니다.
▼ 위치가져오기를 클릭하게 되면 현재 위치의 도시명과 좌표를 가져와서 EditText 에 찍어 줍니다. 그림에서는 위치정보를 가져오기 못하고 있습니다. 왜냐하면 움직임이 없는 에뮬레이터 이기 때문입니다. 하지만 제 스마트폰에서 테스트를 완료하였기 때문에 정상적으로 동작합니다.
▼ 우선 LocationListener 을 이용해서 GPS 변동이 있을 때 값을 가져오기 위해 클래스를 만듭니다. LocationListener 의 onLocationChanged() 함수가 변동이 있을 때 호출되는 함수 입니다. 파라미터로 넘어온 Location 정보로 도시명을 가져와서 화면에 뿌려주는 것이 전부 입니다.
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\n당신의 현재 도시명 : "
+ cityName;
editLocation.setText(s);
▼ activity 가 시작하는 onCreate 함수에서는 LocationManager 객체를 만듭니다. LocationManager 객체에 LocationListener 등록할 것이기 때문입니다.
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
▼ 위치가져오기 버튼을 클릭하게 되면 LocationListener 이용해서 만든 사용자 정의 클래스를 객체화 하게 되며 LocationManager 에 등록합니다. 이전에 GPS 를 사용할수 있도록 옵션에 셋팅되었는지 체크하는 것이 먼저 겠죠.
// Getting GPS status
isGPSEnabled = locationMangaer
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationMangaer
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled && isNetworkEnabled) {
editLocation.setText("방위가 바뀔때 까지 기다려주세요." + "\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10,
locationListener);
} else {
alertbox("Gps 상태!!", "당신의 GPS 상태 : OFF");
}
▼ 이렇게 해서 구현된 메인 activity 의 전체 레이아웃 xml 입니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="1" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:gravity="center"
android:text="현재 도시명 가져오기"
android:textSize="20sp" />
<EditText
android:id="@+id/editTextLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:editable="false" >
<requestFocus>
</requestFocus>
</EditText>
<LinearLayout
android:id="@+id/layButtonH"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:gravity="center" >
<Button
android:id="@+id/btnLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="위치가져오기" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS 멈춤" />
</LinearLayout>
<LinearLayout
android:id="@+id/layloadingH"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:gravity="center" >
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ProgressBar>
</LinearLayout>
</LinearLayout>
▼ 메인 activity 의 전체 소스 입니다. 아래에 LocationListener 을 이용해서 만든 클래스도 포함이 되어있습니다.
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class LocationServiceActivity extends Activity implements
OnClickListener {
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private Button btnGetLocation, btnGpsStop;
private EditText editLocation = null;
private ProgressBar pb = null;
private static final String TAG = "Debug";
private boolean isGPSEnabled = false;
private boolean isNetworkEnabled = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_service);
// if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
btnGpsStop = (Button) findViewById(R.id.btnStop);
btnGpsStop.setOnClickListener(this);
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStop:
locationMangaer.removeUpdates(locationListener);
pb.setVisibility(View.INVISIBLE);
editLocation.setText("");
break;
case R.id.btnLocation:
// Getting GPS status
isGPSEnabled = locationMangaer
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationMangaer
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled && isNetworkEnabled) {
editLocation.setText("방위가 바뀔때 까지 기다려주세요." + "\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10,
locationListener);
} else {
alertbox("Gps 상태!!", "당신의 GPS 상태 : OFF");
}
break;
default:
break;
}
}
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
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);
/*---------- 도시명 가져오기 ----------- */
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\n당신의 현재 도시명 : "
+ cityName;
editLocation.setText(s);
}
@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
}
}
}
'안드로이드 개발' 카테고리의 다른 글
| 안드로이드(Android) PreferenceActivity 이용해서 사용자 정보 셋팅과 정보가져오기 (0) | 2015.03.26 |
|---|---|
| 안드로이드(Android) 스마트폰 맥주소(Mac Address) 확인하는 방법 (1) | 2015.03.09 |
| 안드로이드(Android) GPS 로 현재 이동 속도 알아오기 (5) | 2015.03.05 |
| 안드로이드(Android) Thread 를 이용해 로딩페이지 만들기 (2) | 2015.02.23 |
| 안드로이드(Android) PopupWindow 위젯을 이용해 팝업창 만들기 (5) | 2015.02.08 |
| 안드로이드(Android) 카메라, 갤러리 호출후 이미지 잘래내서 화면에 표시 (12) | 2015.02.05 |
| 안드로이드(Android) Google Map 버전2 에서 PolyLine 이용해 라인,마크 그리기 (0) | 2015.02.02 |
| 안드로이드(Android) Sdcard 미디어 파일 읽어 MP3 실행하기 (0) | 2015.01.29 |
