이 튜토리얼에서는 Android Studio에서 종속성(의존성)을 추가하는 방법을 실제 예제를 통해 단계별로 살펴봅니다. 구글 플레이 서비스의 위치 API(play-services-location)와 런타임 권한 처리 라이브러리인 Dexter를 프로젝트에 추가하고, 이를 활용해 간단한 위치 업데이트 앱을 만들어 보겠습니다.
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"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_start_location_updates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:onClick="startLocationButtonClick"
android:text="@string/start_updates" />
<Button
android:id="@+id/btn_stop_location_updates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:enabled="false"
android:onClick="stopLocationButtonClick"
android:text="@string/stop_updates" />
<Button
android:id="@+id/btn_get_last_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="showLastKnownLocation"
android:text="@string/get_last_location" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center_horizontal"
android:text="Location updates will be received only when app is foreground" />
<TextView
android:id="@+id/location_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textColor="#333"
android:textSize="18sp" />
<TextView
android:id="@+id/updated_on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:textSize="12sp" />
</LinearLayout>3단계 – MainActivity 작성
다음으로 src/MainActivity.java 파일에 아래 코드를 추가합니다. 이 클래스는 FusedLocationProviderClient를 사용해 위치 업데이트를 요청·수신하고, Dexter 라이브러리로 위치 권한을 처리하며, 화면 회전 등 상태 변화 시에도 마지막 위치와 업데이트 시간을 복원하도록 구현되어 있습니다.
package app.com.sample;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.text.DateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
TextView txtLocationResult;
TextView txtUpdatedOn;
Button btnStartUpdates;
Button btnStopUpdates;
// location last updated time
private String mLastUpdateTime;
// location updates interval - 10sec
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
// fastest updates interval - 5 sec
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 5000;
private static final int REQUEST_CHECK_SETTINGS = 100;
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private Location mCurrentLocation;
private Boolean mRequestingLocationUpdates;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
restoreValuesFromBundle(savedInstanceState);
}
private void init() {
txtLocationResult = findViewById(R.id.location_result);
txtUpdatedOn = findViewById(R.id.updated_on);
btnStartUpdates = findViewById(R.id.btn_start_location_updates);
btnStopUpdates = findViewById(R.id.btn_stop_location_updates);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mSettingsClient = LocationServices.getSettingsClient(this);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mCurrentLocation = locationResult.getLastLocation();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateLocationUI();
}
};
mRequestingLocationUpdates = false;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
/**
* Restoring values from saved instance state
*/
private void restoreValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("is_requesting_updates")) {
mRequestingLocationUpdates = savedInstanceState.getBoolean("is_requesting_updates");
}
if (savedInstanceState.containsKey("last_known_location")) {
mCurrentLocation = savedInstanceState.getParcelable("last_known_location");
}
if (savedInstanceState.containsKey("last_updated_on")) {
mLastUpdateTime = savedInstanceState.getString("last_updated_on");
}
}
updateLocationUI();
}
/**
* Update the UI displaying the location data
* and toggling the buttons
*/
private void updateLocationUI() {
if (mCurrentLocation != null) {
txtLocationResult.setText(
"Lat: " + mCurrentLocation.getLatitude() + ", " + "Lng: " + mCurrentLocation.getLongitude()
);
txtLocationResult.setAlpha(0);
txtLocationResult.animate().alpha(1).setDuration(300);
txtUpdatedOn.setText("Last updated on: " + mLastUpdateTime);
}
toggleButtons();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("is_requesting_updates", mRequestingLocationUpdates);
outState.putParcelable("last_known_location", mCurrentLocation);
outState.putString("last_updated_on", mLastUpdateTime);
}
private void toggleButtons() {
if (mRequestingLocationUpdates) {
btnStartUpdates.setEnabled(false);
btnStopUpdates.setEnabled(true);
}
else {
btnStartUpdates.setEnabled(true);
btnStopUpdates.setEnabled(false);
}
}
/**
* Starting location updates
*/
private void startLocationUpdates() {
mSettingsClient
.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
@SuppressLint("MissingPermission")
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.i(TAG, "All location settings are satisfied.");
Toast.makeText(getApplicationContext(), "Started location updates!",
Toast.LENGTH_SHORT).show();
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
updateLocationUI();
}
})
.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
"location settings ");
try {
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
}
catch (IntentSender.SendIntentException sie) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be " + "fixed here. Fix in Settings.";
Log.e(TAG, errorMessage);
Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
updateLocationUI();
}
});
}
public void startLocationButtonClick(View view) {
// Requesting ACCESS_FINE_LOCATION using Dexter library
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
mRequestingLocationUpdates = true;
startLocationUpdates();
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
if (response.isPermanentlyDenied()) {
openSettings();
}
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
public void stopLocationButtonClick(View view) {
mRequestingLocationUpdates = false;
stopLocationUpdates();
}
public void stopLocationUpdates() {
// Removing location updates
mFusedLocationClient
.removeLocationUpdates(mLocationCallback)
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
Toast.makeText(getApplicationContext(), "Location updates stopped!",
Toast.LENGTH_SHORT).show();
toggleButtons();
}
});
}
public void showLastKnownLocation(View view) {
if (mCurrentLocation != null) {
Toast.makeText(getApplicationContext(), "Lat: " + mCurrentLocation.getLatitude() + ", Lng: " + mCurrentLocation.getLongitude(), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Last known location is not available!",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CHECK_SETTINGS) {
switch (resultCode) {
case Activity.RESULT_OK:
Log.e(TAG, "User agreed to make required location settings changes.");
break;
case Activity.RESULT_CANCELED:
Log.e(TAG, "User chose not to make required location settings changes.");
mRequestingLocationUpdates = false;
break;
}
}
}
private void openSettings() {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mRequestingLocationUpdates && checkPermissions()) {
startLocationUpdates();
}
updateLocationUI();
}
private boolean checkPermissions() {
int permissionState = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
return permissionState == PackageManager.PERMISSION_GRANTED;
}
@Override
protected void onPause() {
super.onPause();
if (mRequestingLocationUpdates) {
stopLocationUpdates();
}
}4단계 – build.gradle에 종속성 추가 (핵심)
이제 이 글의 핵심 단계입니다. build.gradle(모듈 수준) 파일의 dependencies 블록에 아래 두 줄을 추가하세요. 첫 번째는 구글 플레이 서비스의 위치 API이고, 두 번째는 런타임 권한 처리를 간편하게 해주는 Dexter 라이브러리입니다.
// location play services implementation 'com.google.android.gms:play-services-location:17.0.0' // dexter runtime permissions implementation 'com.karumi:dexter:4.2.0'
종속성을 추가한 후에는 상단에 나타나는 Sync Now 버튼을 클릭해 Gradle 동기화를 진행해야 변경 사항이 프로젝트에 반영됩니다.
5단계 – AndroidManifest.xml 설정
마지막으로 androidManifest.xml 파일에 아래 코드를 추가하여 정밀 위치(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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 실행(Run) 아이콘을 클릭하세요.
옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.
시작 버튼을 누르면 위치 권한 요청 다이얼로그가 나타나고, 권한을 허용하면 위치 업데이트가 시작되어 위도·경도 값과 마지막 업데이트 시간이 화면에 표시됩니다.