Created
May 12, 2020 20:38
-
-
Save willu2/0679289aad3abc5d28679ef9b1c44883 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
• FusedLocationProviderClient - get location update continuously. | |
implementation 'com.google.android.gms:play-services-location:17.0.0' | |
implementation 'com.google.android.gms:play-services-maps:17.0.0' | |
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> | |
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> | |
<uses-permission android:name="android.permission.INTERNET" /> | |
• MainActivity | |
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { | |
private FusedLocationProviderClient fusedLocationClient; | |
private LocationRequest mLocationRequest; | |
private LocationCallback mlocationCallback; | |
private LocationSettingsRequest.Builder builder; | |
private static final int REQUEST_CHECK_SETTINGS = 102; | |
private GoogleMap mMap; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_maps); | |
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() | |
.findFragmentById(R.id.map); | |
mapFragment.getMapAsync(this); | |
} | |
@Override | |
public void onMapReady(GoogleMap googleMap) { | |
mMap = googleMap; | |
mMap.getUiSettings().setIndoorLevelPickerEnabled(true); | |
mMap.getUiSettings().setAllGesturesEnabled(true); | |
mMap.getUiSettings().setMyLocationButtonEnabled(true); | |
mMap.setOnMapLoadedCallback(this::configLocation); | |
} | |
private void moveCameraPos(LatLng latLng) { | |
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker")); | |
CameraPosition position = CameraPosition.fromLatLngZoom(latLng, 18f); | |
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(position)); | |
} | |
private void configLocation() { | |
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); | |
fetchLastLocation(); | |
mlocationCallback = new LocationCallback() { | |
@Override | |
public void onLocationResult(LocationResult locationResult) { | |
if (locationResult == null) { | |
return; | |
} | |
for (Location location : locationResult.getLocations()) { | |
Log.d("GetLocationUpdate_", "" + location.getLatitude() + "," + location.getLongitude()); | |
mMap.setMyLocationEnabled(true); | |
moveCameraPos(new LatLng(location.getLatitude(), location.getLongitude())); | |
} | |
}; | |
}; | |
mLocationRequest = createLocationRequest(); | |
builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest); | |
checkLocationSetting(builder); | |
} | |
private void fetchLastLocation() { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { | |
showPermissionAlert(); | |
return; | |
} | |
} | |
fusedLocationClient.getLastLocation() | |
.addOnSuccessListener(this, location -> { | |
if (location != null) { | |
Log.d("GetLocationUpdate_", location.getLatitude() + "," + location.getLongitude()); | |
moveCameraPos(new LatLng(location.getLatitude(), location.getLongitude())); | |
} | |
}); | |
} | |
@Override | |
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { | |
if (requestCode == 123) { | |
if (grantResults[0] == PackageManager.PERMISSION_DENIED) { | |
showPermissionAlert(); | |
} else { | |
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { | |
fetchLastLocation(); | |
} | |
} | |
} | |
} | |
private void showPermissionAlert() { | |
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { | |
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 123); | |
} | |
} | |
protected LocationRequest createLocationRequest() { | |
LocationRequest mLocationRequest = LocationRequest.create(); | |
mLocationRequest.setInterval(2000); | |
mLocationRequest.setFastestInterval(1000); | |
mLocationRequest.setSmallestDisplacement(30); | |
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); | |
return mLocationRequest; | |
} | |
private void checkLocationSetting(LocationSettingsRequest.Builder builder) { | |
SettingsClient client = LocationServices.getSettingsClient(this); | |
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build()); | |
task.addOnSuccessListener(this, locationSettingsResponse -> { | |
startLocationUpdates(); | |
return; | |
}); | |
} | |
@Override | |
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { | |
super.onActivityResult(requestCode, resultCode, data); | |
if (requestCode == REQUEST_CHECK_SETTINGS) { | |
if (resultCode == RESULT_OK) { | |
startLocationUpdates(); | |
} else { | |
checkLocationSetting(builder); | |
} | |
} | |
} | |
public void startLocationUpdates() { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { | |
return; | |
} | |
} | |
fusedLocationClient.requestLocationUpdates(mLocationRequest, mlocationCallback, null /* Looper */); | |
} | |
private void stopLocationUpdates() { | |
fusedLocationClient.removeLocationUpdates(mlocationCallback); | |
} | |
} | |
•Layout | |
<?xml version="1.0" encoding="utf-8"?> | |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:tools="http://schemas.android.com/tools" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
android:orientation="vertical"> | |
<fragment | |
android:id="@+id/map" | |
android:name="com.google.android.gms.maps.SupportMapFragment" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
tools:context=".MapsActivity" /> | |
</LinearLayout> | |
• Enable Location Directly | |
private void displayLocationSettingsRequest(Context context) { | |
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context) | |
.addApi(LocationServices.API).build(); | |
googleApiClient.connect(); | |
LocationRequest locationRequest = LocationRequest.create(); | |
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); | |
locationRequest.setInterval(10000); | |
locationRequest.setFastestInterval(10000 / 2); | |
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest); | |
builder.setAlwaysShow(true); | |
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()); | |
result.setResultCallback(result1 -> { | |
final Status status = result1.getStatus(); | |
switch (status.getStatusCode()) { | |
case LocationSettingsStatusCodes.SUCCESS: | |
//Log.d("LocationSettingsStatusCodes", "All location settings are satisfied."); | |
break; | |
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: | |
//Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings "); | |
try { | |
// Show the dialog by calling startResolutionForResult(), and check the result | |
// in onActivityResult(). | |
status.startResolutionForResult(MainActivity.this, 1000); | |
} catch (IntentSender.SendIntentException e) { | |
//Log.i(TAG, "PendingIntent unable to execute request."); | |
} | |
break; | |
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: | |
///Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created."); | |
break; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment