publi void myLocationButtonClicked(){
GpsLocationTracker mGpsLocationTracker = new GpsLocationTracker(activity);
if (mGpsLocationTracker.canGetLocation()) {
latitude = mGpsLocationTracker.getLatitude();
longitude = mGpsLocationTracker.getLongitude();
if ((latitude != 0 && longitude != 0)
} else {
showLocationSnackBar(activity.getString(R.string.wait));
}
} else {
locationChecker();
}
// this function to show dialog to open GPS if it is closed
public void locationChecker() {
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
SettingsClient client = LocationServices.getSettingsClient(activity);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(activity, locationSettingsResponse -> myLocationButtonClicked());
task.addOnFailureListener(activity, e -> {
if (e instanceof ResolvableApiException) {
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(activity,
REQUEST_GPS_RESULT_CODE_FOR_MAP_LOCATION);
} catch (IntentSender.SendIntentException sendEx) {
// Ignore the error.
}
}
});
}
}
это класс GpsLocationTracker
для извлечения местоположения пользователя
public class GpsLocationTracker extends Service implements LocationListener {
/**
* min distance change to get location update
*/
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;
/**
* min time for location update
* 60000 = 1min
*/
private static final long MIN_TIME_FOR_UPDATE = 60000;
/**
* context of calling class
*/
private Context mContext;
/**
* flag for gps status
*/
private boolean isGpsEnabled = false;
/**
* flag for network status
*/
private boolean isNetworkEnabled = false;
/**
* flag for gps
*/
private boolean canGetLocation = false;
/**
* location
*/
private Location mLocation;
/**
* latitude
*/
private double mLatitude;
/**
* longitude
*/
private double mLongitude;
/**
* location manager
*/
private LocationManager mLocationManager;
/**
* @param mContext constructor of the class
*/
public GpsLocationTracker(Context mContext) {
this.mContext = mContext;
getLocation();
}
/**
* @return location
*/
public Location getLocation() {
try {
mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
/*getting status of the gps*/
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*getting status of network provider*/
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) {
/*no location provider enabled*/
} else {
this.canGetLocation = true;
/*getting location from network provider*/
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
/*if gps is enabled then get location using gps*/
if (isGpsEnabled) {
if (mLocation == null) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mLocation;
}
/**
* call this function to stop using gps in your application
*/
public void stopUsingGps() {
if (mLocationManager != null) {
mLocationManager.removeUpdates(GpsLocationTracker.this);
}
}
/**
* @return latitude
* <p/>
* function to get latitude
*/
public double getLatitude() {
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
/**
* @return longitude
* function to get longitude
*/
public double getLongitude() {
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
}
return mLongitude;
}
/**
* @return to check gps or wifi is enabled or not
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* function to prompt user to open
* settings to enable gps
*/
public void showSettingsAlert() {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(new ContextThemeWrapper(mContext, R.style.AppTheme));
mAlertDialog.setTitle(R.string.gps_disabled);
mAlertDialog.setMessage(R.string.enable_gps);
mAlertDialog.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent mIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(mIntent);
}
});
mAlertDialog.setNegativeButton(R.string.dialog_button_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog mcreateDialog = mAlertDialog.create();
mcreateDialog.show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
и когда пользователь нажимает кнопку ОК, вы должны проверить результат в onActivityResult()
.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_GPS_RESULT_CODE_FOR_MAP_LOCATION && resultCode == RESULT_OK)
myLocationButtonClicked();
}