안드로이드 gps를 이용한 현재위치(위도,경도) 구하는 문제입니다.

조회수 17027회

안녕하세요. 안드로이드를 개발중인 학생입니다. gps를 이용하여 어떠한 event발생시 현재 위치의 위도,경도 값을 알고 싶습니다. 여럿 구글링을 통해서 수많은 코드를 복붙했지만 ㅠㅠㅠㅠ 제대로 돌아가는 코드가 없습니다.

제가 알기로는 안드로이드 API버전이 23이 이상이되면서 permission문제가 까다로워져서 이러한 문제가 발생한것 같은데... 특정 event발생시 gps를 이용하여 위도,경도 값을 구하는 방법이 없나요...?

아래는 처음 앱 빌드시 켜지는 activity의

onCreate 함수의 일부분 코드입니다.

Log.d("Main", "onCreate");

    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // GPS 프로바이더 사용가능여부
    isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    // 네트워크 프로바이더 사용가능여부
    isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    Log.d("Main", "isGPSEnabled=" + isGPSEnabled);
    Log.d("Main", "isNetworkEnabled=" + isNetworkEnabled);

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            Toast.makeText(BT_List.this, lat + " " + lng, Toast.LENGTH_SHORT).show();
        }

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

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    // Register the listener with the Location Manager to receive location updates
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

    // 수동으로 위치 구하기
    String locationProvider = LocationManager.GPS_PROVIDER;
    Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
    if (lastKnownLocation != null) {
        double lng = lastKnownLocation.getLatitude();
        double lat = lastKnownLocation.getLatitude();
        Log.d("Main", "longtitude=" + lng + ", latitude=" + lat);
    }
  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)