방위각과 현재 위치 주소를 출력하는 안드로이드 어플리케이션이다.
public class MainActivity extends ActionBarActivity implements SensorEventListener {
TextView sensorText;
TextView locationText;
Button getLocationBtn;
double longitude;
double latitude;
double altitude;
Context context;
private SensorManager sensorManager;
private Sensor sensor;
private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
sensorText = (TextView)findViewById(R.id.resultAzimuth);
locationText = (TextView)findViewById(R.id.resultLocation);
//센서값에 접근하려면 SensorManager과 SensorEventListener을 사용해야한다.
sensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
//sensor 객체는 sensorManger를 통해서 가져온다. 여기서 sensor는 방향 센서이다.
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
/* 화면에 보이기 전에 센서 정보 획득 */
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI); //리스너 object 등록
}
/* 종료될 때 호출되는 메소드 */
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this); //센서를 반납한다.
}
/* 센서 값이 바뀔 때마다 호출되는 메소드이다. */
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
String reusltData = "-- Orientation Sensor -- \n\n"+"\nAzimuth: "+event.values[0] +"\nPitch : "+event.values[1]
+"\nRoll : "+event.values[2];
sensorText.setText(reusltData);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// 센서의 정확도가 변경되었을 때 호출되는 메소드이다.
}
public void getLocationOnClick(View v){
System.out.println("asdasdadassad");
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 1, locationListener);
}catch (SecurityException e){
e.printStackTrace();
}
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
System.out.println(longitude + " , "+latitude);
convertAddr(context, latitude, longitude);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
private void convertAddr(Context context, double lat, double lng){
Geocoder geocoder = new Geocoder(context, Locale.KOREA);
List<Address> address;
String getAddr = null;
try {
if (geocoder != null) {
address = geocoder.getFromLocation(lat, lng, 1);
if(address != null && address.size() > 0){
getAddr = address.get(0).getAddressLine(0).toString();
}
}
locationText.setText(getAddr);
}catch (IOException e){
e.printStackTrace();
}
}
}
반응형