Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 프로그래밍 방식으로 현재 GPS 위치 가져오기: 단계별 완벽 가이드

Android에서 현재 GPS 위치를 프로그래밍 방식으로 얻는 방법

이 예제는 Android 앱에서 FusedLocationProviderClient를 사용해 프로그래밍 방식으로 현재 GPS 위치를 가져오는 방법을 보여줍니다. Google Play 서비스의 통합 위치 API를 활용하면 배터리 효율을 유지하면서 정확한 위치 정보를 손쉽게 조회할 수 있습니다.

1단계 – 새 프로젝트 생성

Android Studio에서 새 프로젝트를 만듭니다. 상단 메뉴에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

2단계 – 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면에는 현재 위치를 표시할 TextView와 위치를 가져오는 버튼이 포함됩니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:gravity="center_horizontal"
    android:orientation="vertical">
    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Current GPS Location"
        android:textSize="24sp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/getLocation"
        android:text="Get location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

3단계 – MainActivity 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다. 이 코드는 위치 권한을 요청하고, 버튼 클릭 시 마지막으로 알려진 위치를 조회해 화면에 출력합니다.

import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class MainActivity extends AppCompatActivity {
    private FusedLocationProviderClient client;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermission();
        client = LocationServices.getFusedLocationProviderClient(this);
        Button button = findViewById(R.id.getLocation);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                client.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener() {
                    @Override
                    public void onSuccess(Location location) {
                        if (location != null) {
                            TextView textView = findViewById(R.id.location);
                            textView.setText(location.toString());
                        }
                    }
                });
            }
        });
    }
    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
    }
}

4단계 – 매니페스트에 권한 추가

androidManifest.xml 파일에 아래 코드를 추가합니다. GPS 위치를 사용하려면 반드시 ACCESS_FINE_LOCATION 권한을 선언해야 합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <uses-permission
        android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 옵션 목록에서 본인의 모바일 기기를 선택하면, 기본 화면과 함께 앱이 실행됩니다.

Android에서 프로그래밍 방식으로 현재 GPS 위치 가져오기: 단계별 완벽 가이드

참고 사항

실제 기기에서 테스트할 때는 설정에서 GPS가 켜져 있어야 하며, 앱 최초 실행 시 위치 권한 허용 팝업이 나타납니다. 에뮬레이터에서 테스트하는 경우 AVD 관리자의 Extended Controls에서 가상 위치를 지정해 확인할 수 있습니다. 또한 getLastLocation()은 마지막으로 저장된 위치를 반환하므로, 실시간 업데이트가 필요하다면 requestLocationUpdates() 사용을 고려해 보세요.