준코딩

GPS를 이용하여 현재 주소 구하기.(Android Java) 본문

프로그래밍/Android(JAVA)

GPS를 이용하여 현재 주소 구하기.(Android Java)

Ljunhyeob - App Dev 2023. 6. 28. 15:47

아래 코드는 위도와 경도를 구하여서 주소로 변환해 보여주는 코드입니다.

 

30분마다 업데이트 하면서 위치를 textView에 보여주고 있습니다.

 

 

public class MainActivity extends AppCompatActivity {
    private TextView txtResult;
    private LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtResult = findViewById(R.id.txtResult);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // 30분마다 위치 정보 업데이트
        final Handler handler = new Handler();
        final int delay = 30 * 1000 * 60; // 30분마다 업데이트
        handler.postDelayed(new Runnable() {
            public void run() {
                getLastKnownLocation();
                startLocationUpdates();
                handler.postDelayed(this, delay);
            }
        }, delay);
    }

    private void getLastKnownLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                updateLocation(location);
            } else {
                showNoLocationToast();
            }
        }
    }

    private void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        }
    }

    @SuppressLint("SetTextI18n")
    private void updateLocation(Location location) {
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();

        long currentTimeMillis = System.currentTimeMillis();
        Date currentTime = new Date(currentTimeMillis);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String formattedTime = sdf.format(currentTime);
        LatLng latLng = new LatLng(latitude, longitude);
        String address = getAddressFromLatLng(this, latLng);
        txtResult.setText("시간 : " + formattedTime + "\n" + "주소 : " + address);
    }

    private String getAddressFromLatLng(Context context, LatLng latLng) {
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        List<Address> addresses;

        try {
            addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
                StringBuilder sb = new StringBuilder();

                // 주소의 각 줄을 StringBuilder에 추가
                for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                    sb.append(address.getAddressLine(i));
                    if (i < address.getMaxAddressLineIndex()) {
                        sb.append(", ");
                    }
                }
                return sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "주소를 찾을 수 없음";
    }

    private void showNoLocationToast() {
        Toast.makeText(this, "현재 위치를 가져올 수 없습니다.", Toast.LENGTH_SHORT).show();
    }

    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            updateLocation(location);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };



}
Comments