매니페스트 파일에 권한 추가
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
package com.example.mylocation
import android.Manifest
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.app.ActivityCompat
import com.example.mylocation.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager // 위치 정보를 담는 관리자
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// 여기서 권한 요청을 하면 된다.
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0f, locationListener()) // 1초 간격으로 실행, 최소 거리값 0f
}
// 위치 정보가 변경됐을 때 호출
internal inner class locationListener : LocationListener {
override fun onLocationChanged(location: Location) {
val geocorder = Geocoder(this@MainActivity) //위도, 경도를 알려주면 우리의 주소를 알려줌.
// 주소 배열을 리스트에 넣어줌. 최대의 결과값을 몇개까지 담아줄지.
val list = geocorder.getFromLocation(location.latitude, location.longitude, 1) as List<Address>
binding.text1.text = "위도: ${location.latitude} 경도: ${location.longitude} 주소: ${list[0].getAddressLine(0)}"
}
}
}