반응형
안드로이드의 기본 라이브러리로 위치정보를 얻기 위해서는 상당히 많은 작업이 필요한다.
google의 play-services의 라이브러리를 이용하면 조금(?)은 쉽게 위치정보를 얻을 수 있습니다.
위치 정보를 얻기 위해서는 권한(Permission)과 권한 요청을 해야 하는데 아래의 포스트를 참고하세요.
1. 모듈(app) gradle에 play-services 라이브러리를 추가하고 Sync Now를 합니다.
android {
...
}
dependencies {
...
implementation 'com.google.android.gms:play-services:12.0.1'
}
2. LocationCallback를 생성하고 onLocationResult(위치정보 변경 시 호출됨) 함수를 오버라이딩한다.
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
if (locationResult == null) {
return
}
for (location in locationResult.locations) {
if (location != null) {
val latitude = location.latitude
val longitude = location.longitude
Log.d("Test", "GPS Location changed, Latitude: $latitude, Longitude: $longitude")
}
}
}
}
3. FusedLocationProviderClient와 LocationRequest 생성하여 위치정보를 요청하면 LocationCallback 클랙스의 onLocationResult 함수가 호출되면 위치정보가 갱신된다.
class MainActivity() : AppCompatActivity() {
...
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
...
val locationRequest = LocationRequest.create()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = 5 * 1000
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}
...
}
4. 아래는 소스로 위치정보 권한 요청과 위치정보 얻어오는 전체 소스입니다. 위의 설명을 토대로 작성되었습니다.
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Looper
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.dksys.visitcall.databinding.ActivityMainBinding
import com.google.android.gms.location.*
class MainActivity() : AppCompatActivity() {
val MY_PERMISSION_ACCESS_ALL = 100
lateinit var binding : ActivityMainBinding
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater);
setContentView(binding.root)
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){
var permissions = arrayOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
)
ActivityCompat.requestPermissions(this, permissions, MY_PERMISSION_ACCESS_ALL)
}else{
requestLocationUpdate()
}
}
override fun finish() {
super.finish()
removeLocationUpdate()
}
@SuppressLint("MissingPermission")
fun requestLocationUpdate(){
val locationRequest = LocationRequest.create()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = 5 * 1000
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}
fun removeLocationUpdate(){
fusedLocationProviderClient.removeLocationUpdates(locationCallback)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode === MY_PERMISSION_ACCESS_ALL) {
if (grantResults.size > 0) {
for (grant in grantResults) {
if (grant != PackageManager.PERMISSION_GRANTED) System.exit(0)
}
requestLocationUpdate()
}
}
}
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
if (locationResult == null) {
return
}
for (location in locationResult.locations) {
if (location != null) {
val latitude = location.latitude
val longitude = location.longitude
Log.d("Test", "GPS Location changed, Latitude: $latitude, Longitude: $longitude")
}
}
}
}
}
반응형
'안드로이드' 카테고리의 다른 글
Android12에서 INSTALL_FAILED_UPDATE_INCOMPATIBLE 오류 (0) | 2022.03.12 |
---|---|
안드로이드 & iOS 앱 화면 디자인 모음 사이트 (0) | 2021.12.28 |
안드로이드 코틀린 - 권한(Permission) 요청 (0) | 2021.09.26 |
안드로이드 코틀린 - 뷰바인딩(View Binding) (0) | 2021.09.25 |
안드로이드 코틀린(Kotlin) - 오류 Module was compiled with an incompatible version of Kotlin. (0) | 2021.09.10 |
댓글