|
25 | 25 | import com.google.android.gms.maps.OnMapReadyCallback;
|
26 | 26 | import com.google.android.gms.maps.SupportMapFragment;
|
27 | 27 | import com.google.android.gms.maps.model.LatLng;
|
28 |
| -import com.google.android.gms.tasks.OnCompleteListener; |
29 |
| -import com.google.android.gms.tasks.Task; |
| 28 | +import com.google.android.gms.tasks.OnFailureListener; |
| 29 | +import com.google.android.gms.tasks.OnSuccessListener; |
30 | 30 |
|
31 | 31 | import permissions.dispatcher.NeedsPermission;
|
32 | 32 | import permissions.dispatcher.RuntimePermissions;
|
@@ -100,18 +100,26 @@ public void onRequestPermissionsResult(int requestCode, String[] permissions, in
|
100 | 100 |
|
101 | 101 | @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
|
102 | 102 | void getMyLocation() {
|
| 103 | + //noinspection MissingPermission |
| 104 | + map.setMyLocationEnabled(true); |
| 105 | + |
103 | 106 | FusedLocationProviderClient locationClient = getFusedLocationProviderClient(this);
|
104 | 107 | //noinspection MissingPermission
|
105 | 108 | locationClient.getLastLocation()
|
106 |
| - .addOnCompleteListener(this, new OnCompleteListener<Location>() { |
| 109 | + .addOnSuccessListener(new OnSuccessListener<Location>() { |
107 | 110 | @Override
|
108 |
| - public void onComplete(@NonNull Task<Location> task) { |
109 |
| - if (task.isSuccessful() && task.getResult() != null) { |
110 |
| - onLocationChanged(task.getResult()); |
111 |
| - } else { |
112 |
| - Log.d("MapDemoActivity", "Error"); |
| 111 | + public void onSuccess(Location location) { |
| 112 | + if (location != null) { |
| 113 | + onLocationChanged(location); |
113 | 114 | }
|
114 | 115 | }
|
| 116 | + }) |
| 117 | + .addOnFailureListener(new OnFailureListener() { |
| 118 | + @Override |
| 119 | + public void onFailure(@NonNull Exception e) { |
| 120 | + Log.d("MapDemoActivity", "Error trying to get last GPS location"); |
| 121 | + e.printStackTrace(); |
| 122 | + } |
115 | 123 | });
|
116 | 124 | }
|
117 | 125 |
|
@@ -197,15 +205,18 @@ public void onLocationResult(LocationResult locationResult) {
|
197 | 205 | }
|
198 | 206 |
|
199 | 207 | public void onLocationChanged(Location location) {
|
| 208 | + // GPS may be turned off |
| 209 | + if (location == null) { |
| 210 | + return; |
| 211 | + } |
| 212 | + |
200 | 213 | // Report to the UI that the location was updated
|
| 214 | + |
201 | 215 | mCurrentLocation = location;
|
202 | 216 | String msg = "Updated Location: " +
|
203 | 217 | Double.toString(location.getLatitude()) + "," +
|
204 | 218 | Double.toString(location.getLongitude());
|
205 | 219 | Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
|
206 |
| - |
207 |
| - //noinspection MissingPermission |
208 |
| - map.setMyLocationEnabled(true); |
209 | 220 | }
|
210 | 221 |
|
211 | 222 | public void onSaveInstanceState(Bundle savedInstanceState) {
|
|
0 commit comments