public class SuccessFragment extends Fragment{
private TextView txtLatitude, txtLongitude, txtAddress;
private FusedLocationProviderClient mFusedLocationClient;
private Location lastLocation;
private LocationRequest locationRequest;
private LocationCallback mLocationCallback;
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 14;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_location, container, false);
txtLatitude = (TextView) view.findViewById(R.id.txtLatitude);
txtLongitude = (TextView) view.findViewById(R.id.txtLongitude);
txtAddress = (TextView) view.findViewById(R.id.txtAddress);
try {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
txtLatitude.setText(String.valueOf(location.getLatitude()));
txtLongitude.setText(String.valueOf(location.getLongitude()));
if (mResultReceiver != null)
txtAddress.setText(mResultReceiver.getAddress());
}
}
});
locationRequest = LocationRequest.create();
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
if (txtAddress.getText().toString().equals(""))
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
else
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
txtLatitude.setText(String.valueOf(location.getLatitude()));
txtLongitude.setText(String.valueOf(location.getLongitude()));
}
}
;
};
} catch (SecurityException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
@Override
public void onStart() {
super.onStart();
if (!checkPermissions()) {
startLocationUpdates();
requestPermissions();
} else {
getLastLocation();
startLocationUpdates();
}
}
@Override
public void onPause() {
stopLocationUpdates();
super.onPause();
}
private boolean checkPermissions() {
int permissionState = ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION);
return permissionState == PackageManager.PERMISSION_GRANTED;
}
private void startLocationPermissionRequest() {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION);
if (shouldProvideRationale) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
showSnackbar(R.string.permission_rationale, android.R.string.ok,
new View.OnClickListener() {
@Override
public void onClick(View view) {
startLocationPermissionRequest();
}
});
} else {
Log.i(TAG, "Requesting permission");
startLocationPermissionRequest();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
} else {
showSnackbar(R.string.permission_denied_explanation, R.string.settings,
new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
@SuppressWarnings("MissingPermission")
private void getLastLocation() {
mFusedLocationClient.getLastLocation()
.addOnCompleteListener(getActivity(), new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
lastLocation = task.getResult();
txtLatitude.setText(String.valueOf(lastLocation.getLatitude()));
txtLongitude.setText(String.valueOf(lastLocation.getLongitude()));
} else {
Log.w(TAG, "getLastLocation:exception", task.getException());
showSnackbar(getString(R.string.no_location_detected));
}
}
});
}
private void stopLocationUpdates() {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationClient.requestLocationUpdates(locationRequest, mLocationCallback, null);
}
private void showSnackbar(final int mainTextStringId, final int actionStringId,
View.OnClickListener listener) {
Snackbar.make(getActivity().findViewById(android.R.id.content),
getString(mainTextStringId),
Snackbar.LENGTH_INDEFINITE)
.setAction(getString(actionStringId), listener).show();
}
}
E il nostro fragment_location.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/locationLayout"
android:layout_below="@+id/txtAddress"
android:layout_width="match_parent"
android:layout_height="@dimen/activity_margin_30dp"
android:orientation="horizontal">
<TextView
android:id="@+id/txtLatitude"
android:layout_width="@dimen/activity_margin_0dp"
android:layout_height="@dimen/activity_margin_30dp"
android:layout_weight="0.5"
android:gravity="center"
android:hint="@string/latitude"
android:textAllCaps="false"
android:textColorHint="@color/colorPrimaryDark"
android:textColor="@color/colorPrimaryDark" />
<TextView
android:id="@+id/txtLongitude"
android:layout_width="@dimen/activity_margin_0dp"
android:layout_height="@dimen/activity_margin_30dp"
android:layout_weight="0.5"
android:gravity="center"
android:hint="@string/longitude"
android:textAllCaps="false"
android:textColorHint="@color/colorPrimary"
android:textColor="@color/colorPrimary" />
</LinearLayout>