[Android] GPS 내 위치정보 가져오기

Kim Hyunjun·2023년 12월 12일

Android Studio

목록 보기
2/3
  1. AndroidManifest.xml 파일을 열어 제껴서 두 줄을 추가해야 한다.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

나는 그냥 ACCESS_FINE_LOCATION 만 넣으려고 했는데 위에 것 안넣으면 오류 뜬다나 뭐라나


  1. 대충 버튼 누르면 위도 경도 출력하는 코드.
public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 1;
    private LocationManager locationManager;
    private Button getLocationButton;

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

        getLocationButton = findViewById(R.id.getLocationButton); // Replace with your button ID

        // Check for location permission
        if (ContextCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {
            // Request permission if not granted
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSION_REQUEST_CODE
            );
        } else {
            // Permission already granted, start location updates
            startLocationUpdates();
        }

        getLocationButton.setOnClickListener(view -> {
            // When the button is clicked, show the Toast with the current location
            showCurrentLocation();
        });
    }

    private void startLocationUpdates() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // Check if GPS is enabled
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            // Register for location updates
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    1000,   // minimum time interval between updates (milliseconds)
                    1,      // minimum distance between updates (meters)
                    new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            // Handle location change
                            double latitude = location.getLatitude();
                            double longitude = location.getLongitude();
                            // Update the location whenever it changes
                            updateLocation(latitude, longitude);
                        }

                        @Override
                        public void onStatusChanged(String provider, int status, Bundle extras) {
                            // Do nothing
                        }

                        @Override
                        public void onProviderEnabled(String provider) {
                            // Do nothing
                        }

                        @Override
                        public void onProviderDisabled(String provider) {
                            // Do nothing
                        }
                    }
            );
        } else {
            // GPS is not enabled, prompt the user to enable it
            // You can customize this part according to your app's requirements
            Toast.makeText(
                    this,
                    "Please enable GPS for location updates",
                    Toast.LENGTH_LONG
            ).show();
        }
    }
    private void updateLocation(double latitude, double longitude) {
        // You can update the UI or perform any other actions with the location data
        // For now, we'll just show a Toast message
        Toast.makeText(
                this,
                "Latitude: " + latitude + "\nLongitude: " + longitude,
                Toast.LENGTH_SHORT
        ).show();
    }
}



만들던 중에

Xml 이제 안쓴다는데 이것 밖에 모르면 이거라도 써야한다.

버튼 놈이 자꾸 오른쪽 벽에 안뜨길래 개고생했다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity3">
    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_gravity="right"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>

이런 식으로 버튼 놈을 LinearLayout 으로 묶어서 orientation 을 verical 로 바꿔주면 해결이 되었다.

xml 에서 SearchView 가 오류가 뜨듯 빨간색으로 바뀌었는데
이제 서비스를 안하는지 것도 체크해봐야겠다.

profile
모방가

0개의 댓글