Skip to content
This repository was archived by the owner on Aug 23, 2023. It is now read-only.

Commit 01be1dd

Browse files
committed
BasicLocationKotlin module:
-refactored MainActivity for using ViewBinding instead of findViewById and Java 8 features -replaced deprecated BuildConfig.APPLICATION_ID with BuildConfig.LIBRARY_PACKAGE_NAME -MainActivity: reorganised methods
1 parent c6c0297 commit 01be1dd

File tree

2 files changed

+85
-98
lines changed

2 files changed

+85
-98
lines changed

BasicLocationKotlin/app/src/main/java/com/google/android/gms/location/sample/basiclocationsample/MainActivity.kt

Lines changed: 83 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -19,52 +19,49 @@ package com.google.android.gms.location.sample.basiclocationsample
1919
import android.Manifest.permission.ACCESS_COARSE_LOCATION
2020
import android.annotation.SuppressLint
2121
import android.content.Intent
22-
import android.content.pm.PackageManager
2322
import android.content.pm.PackageManager.PERMISSION_GRANTED
24-
import android.location.Location
2523
import android.net.Uri
2624
import android.os.Bundle
2725
import android.provider.Settings
28-
import com.google.android.material.snackbar.Snackbar
29-
import com.google.android.material.snackbar.Snackbar.LENGTH_INDEFINITE
30-
import com.google.android.material.snackbar.Snackbar.LENGTH_LONG
31-
import androidx.core.app.ActivityCompat
32-
import androidx.appcompat.app.AppCompatActivity
3326
import android.util.Log
3427
import android.view.View
35-
import android.widget.TextView
36-
28+
import androidx.appcompat.app.AppCompatActivity
29+
import androidx.core.app.ActivityCompat
30+
import androidx.viewbinding.BuildConfig
3731
import com.google.android.gms.location.FusedLocationProviderClient
3832
import com.google.android.gms.location.LocationServices
39-
import com.google.android.gms.location.sample.basiclocationsample.BuildConfig.APPLICATION_ID
40-
import com.google.android.gms.tasks.Task
33+
import com.google.android.gms.location.sample.basiclocationsample.databinding.MainActivityBinding
34+
import com.google.android.material.snackbar.Snackbar
35+
import com.google.android.material.snackbar.Snackbar.LENGTH_INDEFINITE
4136

4237
/**
4338
* Demonstrates use of the Location API to retrieve the last known location for a device.
4439
*/
45-
class MainActivity : AppCompatActivity() {
46-
40+
class MainActivity: AppCompatActivity() {
4741
private val TAG = "MainActivity"
4842
private val REQUEST_PERMISSIONS_REQUEST_CODE = 34
4943

5044
/**
5145
* Provides the entry point to the Fused Location Provider API.
5246
*/
5347
private lateinit var fusedLocationClient: FusedLocationProviderClient
54-
55-
private lateinit var latitudeText: TextView
56-
private lateinit var longitudeText: TextView
48+
49+
/**
50+
* ViewBinding
51+
*/
52+
private lateinit var binding: MainActivityBinding
5753

5854
override fun onCreate(savedInstanceState: Bundle?) {
5955
super.onCreate(savedInstanceState)
60-
setContentView(R.layout.main_activity)
61-
62-
latitudeText = findViewById(R.id.latitude_text)
63-
longitudeText = findViewById(R.id.longitude_text)
56+
57+
// ViewBinding initialization
58+
binding = MainActivityBinding.inflate(layoutInflater)
59+
val view = binding.root
60+
setContentView(view)
6461

6562
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
6663
}
67-
64+
6865
override fun onStart() {
6966
super.onStart()
7067

@@ -74,75 +71,21 @@ class MainActivity : AppCompatActivity() {
7471
getLastLocation()
7572
}
7673
}
77-
78-
/**
79-
* Provides a simple way of getting a device's location and is well suited for
80-
* applications that do not require a fine-grained location and that do not need location
81-
* updates. Gets the best and most recent location currently available, which may be null
82-
* in rare cases when a location is not available.
83-
*
84-
* Note: this method should be called after location permission has been granted.
85-
*/
86-
@SuppressLint("MissingPermission")
87-
private fun getLastLocation() {
88-
fusedLocationClient.lastLocation
89-
.addOnCompleteListener { taskLocation ->
90-
if (taskLocation.isSuccessful && taskLocation.result != null) {
91-
92-
val location = taskLocation.result
93-
94-
latitudeText.text = resources
95-
.getString(R.string.latitude_label, location?.latitude)
96-
longitudeText.text = resources
97-
.getString(R.string.longitude_label, location?.longitude)
98-
} else {
99-
Log.w(TAG, "getLastLocation:exception", taskLocation.exception)
100-
showSnackbar(R.string.no_location_detected)
101-
}
102-
}
103-
}
104-
105-
/**
106-
* Shows a [Snackbar].
107-
*
108-
* @param snackStrId The id for the string resource for the Snackbar text.
109-
* @param actionStrId The text of the action item.
110-
* @param listener The listener associated with the Snackbar action.
111-
*/
112-
private fun showSnackbar(
113-
snackStrId: Int,
114-
actionStrId: Int = 0,
115-
listener: View.OnClickListener? = null
116-
) {
117-
val snackbar = Snackbar.make(findViewById(android.R.id.content), getString(snackStrId),
118-
LENGTH_INDEFINITE)
119-
if (actionStrId != 0 && listener != null) {
120-
snackbar.setAction(getString(actionStrId), listener)
121-
}
122-
snackbar.show()
123-
}
124-
12574
/**
12675
* Return the current state of the permissions needed.
12776
*/
128-
private fun checkPermissions() =
129-
ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) == PERMISSION_GRANTED
130-
131-
private fun startLocationPermissionRequest() {
132-
ActivityCompat.requestPermissions(this, arrayOf(ACCESS_COARSE_LOCATION),
133-
REQUEST_PERMISSIONS_REQUEST_CODE)
134-
}
135-
77+
private fun checkPermissions() = ActivityCompat.checkSelfPermission(this,
78+
ACCESS_COARSE_LOCATION) == PERMISSION_GRANTED
13679
private fun requestPermissions() {
13780
if (ActivityCompat.shouldShowRequestPermissionRationale(this, ACCESS_COARSE_LOCATION)) {
13881
// Provide an additional rationale to the user. This would happen if the user denied the
13982
// request previously, but didn't check the "Don't ask again" checkbox.
14083
Log.i(TAG, "Displaying permission rationale to provide additional context.")
141-
showSnackbar(R.string.permission_rationale, android.R.string.ok, View.OnClickListener {
84+
showSnackbar(R.string.permission_rationale, android.R.string.ok) {
14285
// Request permission
14386
startLocationPermissionRequest()
144-
})
145-
87+
}
88+
14689
} else {
14790
// Request permission. It's possible this can be auto answered if device policy
14891
// sets the permission in a given state or the user denied the permission
@@ -151,7 +94,10 @@ class MainActivity : AppCompatActivity() {
15194
startLocationPermissionRequest()
15295
}
15396
}
154-
97+
private fun startLocationPermissionRequest() {
98+
ActivityCompat.requestPermissions(this, arrayOf(ACCESS_COARSE_LOCATION),
99+
REQUEST_PERMISSIONS_REQUEST_CODE)
100+
}
155101
/**
156102
* Callback received when a permissions request has been completed.
157103
*/
@@ -166,35 +112,76 @@ class MainActivity : AppCompatActivity() {
166112
// If user interaction was interrupted, the permission request is cancelled and you
167113
// receive empty arrays.
168114
grantResults.isEmpty() -> Log.i(TAG, "User interaction was cancelled.")
169-
115+
170116
// Permission granted.
171-
(grantResults[0] == PackageManager.PERMISSION_GRANTED) -> getLastLocation()
172-
117+
(grantResults[0] == PERMISSION_GRANTED) -> getLastLocation()
118+
173119
// Permission denied.
174-
120+
175121
// Notify the user via a SnackBar that they have rejected a core permission for the
176122
// app, which makes the Activity useless. In a real app, core permissions would
177123
// typically be best requested during a welcome-screen flow.
178-
124+
179125
// Additionally, it is important to remember that a permission might have been
180126
// rejected without asking the user for permission (device policy or "Never ask
181127
// again" prompts). Therefore, a user interface affordance is typically implemented
182128
// when permissions are denied. Otherwise, your app could appear unresponsive to
183129
// touches or interactions which have required permissions.
184130
else -> {
185-
showSnackbar(R.string.permission_denied_explanation, R.string.settings,
186-
View.OnClickListener {
187-
// Build intent that displays the App settings screen.
188-
val intent = Intent().apply {
189-
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
190-
data = Uri.fromParts("package", APPLICATION_ID, null)
191-
flags = Intent.FLAG_ACTIVITY_NEW_TASK
192-
}
193-
startActivity(intent)
194-
})
131+
showSnackbar(R.string.permission_denied_explanation, R.string.settings) {
132+
// Build intent that displays the App settings screen.
133+
val intent = Intent().apply {
134+
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
135+
data = Uri.fromParts("package",
136+
BuildConfig.LIBRARY_PACKAGE_NAME, null)
137+
flags = Intent.FLAG_ACTIVITY_NEW_TASK
138+
}
139+
startActivity(intent)
140+
}
195141
}
196142
}
197143
}
198144
}
145+
/**
146+
* Provides a simple way of getting a device's location and is well suited for
147+
* applications that do not require a fine-grained location and that do not need location
148+
* updates. Gets the best and most recent location currently available, which may be null
149+
* in rare cases when a location is not available.
150+
*
151+
* Note: this method should be called after location permission has been granted.
152+
*/
153+
@SuppressLint("MissingPermission")
154+
private fun getLastLocation() {
155+
fusedLocationClient.lastLocation
156+
.addOnCompleteListener { taskLocation ->
157+
if (taskLocation.isSuccessful && taskLocation.result != null) {
158+
159+
val location = taskLocation.result
199160

161+
binding.currentLatitude.text = resources
162+
.getString(R.string.latitude_label, location?.latitude)
163+
binding.currentLongitude.text = resources
164+
.getString(R.string.longitude_label, location?.longitude)
165+
} else {
166+
Log.w(TAG, "getLastLocation:exception", taskLocation.exception)
167+
showSnackbar(R.string.no_location_detected)
168+
}
169+
}
170+
}
171+
/**
172+
* Shows a [Snackbar].
173+
*
174+
* @param snackStrId The id for the string resource for the Snackbar text.
175+
* @param actionStrId The text of the action item.
176+
* @param listener The listener associated with the Snackbar action.
177+
*/
178+
private fun showSnackbar(snackStrId: Int, actionStrId: Int = 0,
179+
listener: View.OnClickListener? = null) {
180+
val snackBar = Snackbar.make(findViewById(android.R.id.content), getString(snackStrId),
181+
LENGTH_INDEFINITE)
182+
if (actionStrId != 0 && listener != null) {
183+
snackBar.setAction(getString(actionStrId), listener)
184+
}
185+
snackBar.show()
186+
}
200187
}

BasicLocationKotlin/app/src/main/res/layout/main_activity.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
android:paddingTop="@dimen/activity_vertical_margin">
2727

2828
<TextView
29-
android:id="@+id/latitude_text"
29+
android:id="@+id/current_latitude"
3030
android:layout_width="wrap_content"
3131
android:layout_height="wrap_content"
3232
android:layout_marginLeft="@dimen/margin_start"
@@ -35,7 +35,7 @@
3535
android:textSize="@dimen/lat_long_text_size" />
3636

3737
<TextView
38-
android:id="@+id/longitude_text"
38+
android:id="@+id/current_longitude"
3939
android:layout_width="wrap_content"
4040
android:layout_height="wrap_content"
4141
android:layout_marginLeft="@dimen/margin_start"

0 commit comments

Comments
 (0)