Skip to content

Commit e4be22e

Browse files
authored
Merge pull request #13 from rogerhu/fbu
Make onSuccess and onFailure() listeners more explicit
2 parents 2023624 + 1f27ff0 commit e4be22e

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

app/src/main/java/com/example/mapdemo/MapDemoActivity.java

+22-11
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@
2525
import com.google.android.gms.maps.OnMapReadyCallback;
2626
import com.google.android.gms.maps.SupportMapFragment;
2727
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;
3030

3131
import permissions.dispatcher.NeedsPermission;
3232
import permissions.dispatcher.RuntimePermissions;
@@ -100,18 +100,26 @@ public void onRequestPermissionsResult(int requestCode, String[] permissions, in
100100

101101
@NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
102102
void getMyLocation() {
103+
//noinspection MissingPermission
104+
map.setMyLocationEnabled(true);
105+
103106
FusedLocationProviderClient locationClient = getFusedLocationProviderClient(this);
104107
//noinspection MissingPermission
105108
locationClient.getLastLocation()
106-
.addOnCompleteListener(this, new OnCompleteListener<Location>() {
109+
.addOnSuccessListener(new OnSuccessListener<Location>() {
107110
@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);
113114
}
114115
}
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+
}
115123
});
116124
}
117125

@@ -197,15 +205,18 @@ public void onLocationResult(LocationResult locationResult) {
197205
}
198206

199207
public void onLocationChanged(Location location) {
208+
// GPS may be turned off
209+
if (location == null) {
210+
return;
211+
}
212+
200213
// Report to the UI that the location was updated
214+
201215
mCurrentLocation = location;
202216
String msg = "Updated Location: " +
203217
Double.toString(location.getLatitude()) + "," +
204218
Double.toString(location.getLongitude());
205219
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
206-
207-
//noinspection MissingPermission
208-
map.setMyLocationEnabled(true);
209220
}
210221

211222
public void onSaveInstanceState(Bundle savedInstanceState) {

0 commit comments

Comments
 (0)