Android, 사용자위치

이도현·2023년 8월 11일
0

Android 공부

목록 보기
9/30

1. 위치 정보 액세스 권한 요청

// 예시, Androidmanifest.xml
	<uses-permission android:name ="android.permission.ACCESS_BACKGROUND_LOCATION"/>
  <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  • 안드로이드 11이전과 이후가 다르므로 공식문서확인

https://developer.android.com/training/location/permissions?hl=ko

2. 마지막으로 알려진 위치 가져오기

1) 위치 서비스 클라이언트 만들기

private lateinit var fusedLocationClient: FusedLocationProviderClient

override fun onCreate(savedInstanceState: Bundle?) {
    // ...

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}

2) 마지막으로 알려진 위치 가져오기

if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        fusedLocationClient.lastLocation
                .addOnSuccessListener { location: Location? ->
                        //Got last know location. In Some rare situation this can be null
                }
}

// 권한 문제해결을 위해 if문이 들어가야함.

3) 위치설정변경

fun createLocationRequset(){
        val locationRequest = LocationRequest.create()?.apply{
                interval = 5000
                fastestInterval = 3000
                priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

				// 현재 위치 설정받기
        if(locationRequest != null){
                val builder = LocationSettingsRequest.Builder()
                        .addLocationRequest(locationRequest)
                val client: SettingsClient = LocationServices.getSettingsClient(this)
                val task:Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())
                // tak가 완료되면 LocationSettingsResponse객체의 상태 코드로 위치설정을 확인
								task.addOnSuccessListener { locationSettingsResponse ->
                        // All location settings are satisfied. The Client can initialize
                        // locaiton resquest here
                        // ...
                }
// 사용자에게 위치설정을 변경하라는 메시지 표시
                task.addOnFailureListener { exception ->
                        if(exception is ResolvableApiException){
                                // Location settings are not setistfy
                                // by showin the user a dialog
                                try{
                                        //Show the dialog by calling startResolutionForResult()
                                        // and check the result in onActivityResult().
                                        exception.startResolutionForResult(this@MainActivity, Log.e("error","error"))
                                } catch (sendEx: IntentSender.SendIntentException){
                                        // Ingnore Error
                                }
                        }

                }
        }
}
  • interval: 앱에서 선호하는 위치 업데이트 수신 간격
  • fastestInterval: 앱이 위치 업데이트를 할 수 있는 가장 빠른 간격
  • 우선순위
    • PRIORITY_BALANCED_POWER_ACCURACY: 대략 100미터, wi-fi와 휴대폰 기지국 위치를 사용할 수 있습니다.
    • PRIORITY_HIGH_ACCURACY: 가장 정확한 위치 요청
    • PRIORITY_LOW_POWR: 도시 수준의 정밀도 요청, 전력 아낌
    • PRIORITY_NO_POWER: 전력 소비에 영향을 많이 미치지 않으며 이 설정을 사용하면 다른앱에서 트리거한 위치를 수신

3. 예시 코드

import android.content.ContentValues.TAG
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Looper
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat
import com.example.scatter.ui.theme.ScatterTheme
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

class MainActivity : ComponentActivity() {
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var locationCallback: LocationCallback

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ScatterTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Greeting("Android")
                }
            }
        }
    }
    // 통합 위치 제공자 초기화
    private fun initLocationClient(){
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)

        val locationRequest = LocationRequest.create()?.apply{
            interval = 1000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

        val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest!!)
        val client = LocationServices.getSettingsClient(context)
        val task = client.checkLocationSettings(builder.build())
        task.addOnSuccessListener {
            Log.d(TAG, "location client setting success")
        }
        task.addOnFailureListener {
            Log.d(TAG, "location client setting fail")
        }
    }

    // 마지막으로 알려진 위치 요청
    fun requestLastLocation(){
        if(ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )!= PackageManager.PERMISSION_GRANTED&&ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        fusedLocationClient.lastLocation
            .addOnSuccessListener { location ->
                listener.onLocationUpdated(location)
            }

    }

    //위치 업데이트 초기화
    private fun iniLocationCallback(){
        locationCallback = object : LocationCallback(){
            override fun onLocationResult(locationResult: LocationResult?){
                locationResult ?: return
                for(location in locationResult.locations){
                    listener.onLocationUpdated(location)
                    break
                }
            }
        }
    }

    fun startLocationUpdates(){
        if(ActivityCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        val locationRequest = LocationRequest.create()?.apply{
            interval = 1000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }
        fusedLocationClient.requestLocationUpdates(
            locationRequest!!,
            locationCallback,
            Looper.getMainLooper()
        )
    }
}
profile
좋은 지식 나누어요

0개의 댓글