Android 프로그래밍 2

본문 바로가기
사이트 내 전체검색


Android 프로그래밍 2
Android 프로그래밍 2

4. LocationListener With Kotlin

페이지 정보

작성자 관리자 댓글 0건 조회 2,331회 작성일 20-03-15 16:58

본문

4. LocationListener With Kotlin

우리가 일상 생활에서 사용하는 많은 안드로이드 응용 프로그램에는 사용자의 현재 위치가 지속적으로 필요합니다. 

여기서는 FusedLocationProviderClient를 사용하여 Kotlin으로 LocationListener를 구현할 것입니다.



1. 새 프로젝트 추가

 

프로젝트명 : LocationListener



2. 권한 및 종속성 추가

 

장치에서 위치에 액세스하려면 manifest 파일에 다음 권한을 추가하십시오. 


<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 

 

build.gradle (Module : app) 파일에 다음 종속성을 추가하십시오. 


dependencies {
implementation 'com.google.android.gms:play-services-location:16.0.0'

 

 


3. 레이아웃 파일 설정

 

홈 화면의 레이아웃 파일을 설정하십시오. 아래와 같이 두 개의 버튼과 세 개의 TextView가 있습니다. 



파일명 : activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_start_upds"
android:layout_width="match_parent"
android:layout_marginRight="12dp"
android:layout_marginLeft="12dp"
android:layout_marginTop="24dp"
android:layout_height="wrap_content"
android:text="Start Location UPDates" />
<Button
android:enabled="false"
android:id="@+id/btn_stop_upds"
android:layout_width="match_parent"
android:layout_marginRight="12dp"
android:layout_marginLeft="12dp"
android:layout_height="wrap_content"
android:text="Stop Location UPDates" />
<TextView
android:padding="12dp"
android:layout_marginTop="12dp"
android:textSize="18sp"
android:layout_marginRight="12dp"
android:layout_marginLeft="12dp"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:id="@+id/txtLat"
/>
<TextView
android:padding="12dp"
android:layout_gravity="center_horizontal"
android:textSize="18sp"
android:layout_marginRight="12dp"
android:layout_marginLeft="12dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtLong"
/>
<TextView
android:layout_gravity="center_horizontal"
android:padding="12dp"
android:textSize="18sp"
android:layout_marginRight="12dp"
android:layout_marginLeft="12dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtTime" />
</LinearLayout>

 

 



 

4. MainActivity 설정

 

여기서는 MainActivity.kt 클래스에서 위치 리스너를 구현하는 방법에 대해 자세히 설명합니다.

먼저 초기화해야합니다

 

권한 확인

 

런타임에 필요한 모든 권한을 허용했는지 확인해야합니다.

런타임 권한을 표시하기 위해 이미 매니페스트 파일에 권한을 추가했습니다. 

다음 방법을 수행해야합니다. 


fun checkPermissionForLocation(context: Context): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED){
true
}else{
// Show the permission request
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_PERMISSION_LOCATION)
false
}
} else {
true
}
}

 

이제 사용자가 권한을 부여했는지 확인하기 위해 onRequestPermissionsResult 메소드를 구현해야합니다. 


override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == REQUEST_PERMISSION_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//We have to add startlocationUpdate() method later instead of Toast
Toast.makeText(this,"Permission granted",Toast.LENGTH_SHORT).show()
}
}
}

 

 

위치 확인

 

위치를 확인하려면 프로젝트에 다음 코드를 추가해야합니다. 



private fun buildAlertMessageNoGps() {
val builder = AlertDialog.Builder(this)
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes") { dialog, id ->
startActivityForResult(
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
, 11)
}
.setNegativeButton("No") { dialog, id ->
dialog.cancel()
finish()
}
val alert: AlertDialog = builder.create()
alert.show()
}


 

LocationListener 설정

 

이제 startLocationUpdates () 메소드를 사용하여 LocationListener를 설정하겠습니다. 

그 전에 아래 주어진 LocationCallback을 추가해야합니다.


    private val mLocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
// do work here
locationResult.lastLocation
onLocationChanged(locationResult.lastLocation)
}
}

fun onLocationChanged(location: Location) {
// New location has now been determined

mLastLocation = location
if (mLastLocation != null) {
// Update the UI from here
}
}

 

 

이제 다음과 같이 startLocationUpdates () 메소드를 코드에 추가하십시오.


protected fun startLocationUpdates() {
// Create the location request to start receiving updates
mLocationRequest = LocationRequest()
mLocationRequest!!.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
mLocationRequest!!.setInterval(INTERVAL)
mLocationRequest!!.setFastestInterval(FASTEST_INTERVAL)

// Create LocationSettingsRequest object using location request
val builder = LocationSettingsRequest.Builder()
builder.addLocationRequest(mLocationRequest!!)
val locationSettingsRequest = builder.build()

val settingsClient = LocationServices.getSettingsClient(this)
settingsClient.checkLocationSettings(locationSettingsRequest)

mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return
}
mFusedLocationProviderClient!!.requestLocationUpdates(mLocationRequest, mLocationCallback,
Looper.myLooper())
}

 

 

위치 업데이트를 중지하려면 다음을 추가하십시오.



private fun stoplocationUpdates() {
mFusedLocationProviderClient!!.removeLocationUpdates(mLocationCallback)
}

 


이제 모두 프로젝트를 실행하도록 설정되었습니다.


onCreate() 메소드에 startLocationUpdates()을 추가하여 앱이 시작시 실행하도록 설정한다.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

mLocationRequest = LocationRequest()

btnStartupdate = findViewById(R.id.btn_start_upds)
btnStopUpdates = findViewById(R.id.btn_stop_upds)
txtLat = findViewById(R.id.txtLat);
txtLong = findViewById(R.id.txtLong);
txtTime = findViewById(R.id.txtTime);

val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps()
}


btnStartupdate.setOnClickListener {
if (checkPermissionForLocation(this)) {
startLocationUpdates()
btnStartupdate.isEnabled = false
btnStopUpdates.isEnabled = true
}
}

btnStopUpdates.setOnClickListener {
stoplocationUpdates()
txtTime.text = "Updates Stoped"
btnStartupdate.isEnabled = true
btnStopUpdates.isEnabled = false
}

}

 

 


 

댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.