[#105][안드로이드] 위치정보(위도, 경도)를 주소로 변환하기 (Geocoder)
[안드로이드] 위치정보(위도, 경도)를 주소로 변환하기 (Geocoder)
1. GPSInfo.java
package com.example.ghd_t.myapplication;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.Log;
/**
* Created by ghd-t on 2018-04-23.
*/
public class GPSInfo extends Service implements LocationListener{
private final Context mContext;
// 현재 GPS 사용유무
boolean isGPSEnabled = false;
// 네트워크 사용유무
boolean isNetworkEnabled = false;
// GPS 상태값
boolean isGetLocation = false;
Location location;
double lat; // 위도
double lon; // 경도
// 최소 GPS 정보 업데이트 거리 10미터
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
// 최소 GPS 정보 업데이트 시간 밀리세컨(1분)
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSInfo(Context context) {
this.mContext = context;
getLocation();
}
@TargetApi(23)
public Location getLocation() {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(
mContext, android.Manifest.permission.ACCESS_FINE_LOCATION )
!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return null;
}
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// GPS 정보 가져오기
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// 현재 네트워크 상태 값 알아오기
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// GPS 와 네트워크사용이 가능하지 않을때 소스 구현
} else {
this.isGetLocation = true;
// 네트워크 정보로 부터 위치값 가져오기
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
// 위도 경도 저장
lat = location.getLatitude();
lon = location.getLongitude();
Log.v("알림", "위도 : " + lat + "경도 " + lon);
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
//gps종료
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSInfo.this);
}
}
//위도값 가져오기
public double getLatitude(){
if(location != null){
lat = location.getLatitude();
}
return lat;
}
//경도값 가져오기
public double getLongitude(){
if(location != null){
lon = location.getLongitude();
}
return lon;
}
//gps가 켜져있는지 확인
public boolean isGetLocation() {
return this.isGetLocation;
}
//gps설정 정보를 가져올 수 없을 때
public void showSettingsAlert(){
makeDialog();
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
private void makeDialog(){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(mContext);
alt_bld.setMessage("GPS 사용이 필요합니다. \n설정창으로 가시겠습니까?").setCancelable(
false).setPositiveButton("네",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// 네 클릭
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
}).setNegativeButton("아니오",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// 아니오 클릭. dialog 닫기.
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// 대화창 클릭시 뒷 배경 어두워지는 것 막기
//alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
// 대화창 제목 설정
alert.setTitle("GPS 사용 허가");
// 대화창 아이콘 설정
alert.setIcon(R.drawable.check_dialog_64);
// 대화창 배경 색 설정
alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(255,62,79,92)));
alert.show();
}
}
| cs |
2. HomeFragment.java에서 호출
package com.example.ghd_t.myapplication;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
private final int PERMISSIONS_ACCESS_FINE_LOCATION = 1000;
private final int PERMISSIONS_ACCESS_COARSE_LOCATION = 1001;
private boolean isAccessFineLocation = false;
private boolean isAccessCoarseLocation = false;
private boolean isPermission = false;
private GPSInfo gps;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
Button btn_gps = view.findViewById(R.id.gps);
btn_gps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!isPermission){
callPermission();
return;
}
gps = new GPSInfo(getContext());
// GPS 사용유무 가져오기
if (gps.isGetLocation()) {
//GPSInfo를 통해 알아낸 위도값과 경도값
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
//Geocoder
Geocoder gCoder = new Geocoder(getContext(), Locale.getDefault());
List<Address> addr = null;
try{
addr = gCoder.getFromLocation(latitude,longitude,1);
Address a = addr.get(0);
for (int i=0;i <= a.getMaxAddressLineIndex();i++) {
//여기서 변환된 주소 확인할 수 있음
Log.v("알림", "AddressLine(" + i + ")" + a.getAddressLine(i) + "\n");
}
} catch (IOException e){
e.printStackTrace();
}
if (addr != null) {
if (addr.size()==0) {
Toast.makeText(getContext(),"주소정보 없음", Toast.LENGTH_LONG).show();
}
}
} else {
// GPS 를 사용할수 없으므로
gps.showSettingsAlert();
}
}
});
callPermission(); // 권한 요청을 해야 함
return view;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == PERMISSIONS_ACCESS_FINE_LOCATION
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isAccessFineLocation = true;
} else if (requestCode == PERMISSIONS_ACCESS_COARSE_LOCATION
&& grantResults[0] == PackageManager.PERMISSION_GRANTED){
isAccessCoarseLocation = true;
}
if (isAccessFineLocation && isAccessCoarseLocation) {
isPermission = true;
}
}
// 전화번호 권한 요청
private void callPermission() {
// Check the SDK version and whether the permission is already granted or not.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_ACCESS_FINE_LOCATION);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_ACCESS_COARSE_LOCATION);
} else {
isPermission = true;
}
}
}
| cs |
3. 결과물
GPS사용 허가 후 시도했을 때
댓글
댓글 쓰기