Skip to content

Instantly share code, notes, and snippets.

@jobinjj
Created November 30, 2019 11:59
Show Gist options
  • Save jobinjj/e85c6791b0f92b8a7ece2d226ee00590 to your computer and use it in GitHub Desktop.
Save jobinjj/e85c6791b0f92b8a7ece2d226ee00590 to your computer and use it in GitHub Desktop.
public class Main2Activity extends AppCompatActivity {
private SettingsClient mSettingsClient;
public static final int REQUEST_LOCATION_PERMISSION = 100;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 5000;
public static final int REQUEST_CHECK_SETTINGS = 100;
private LocationSettingsRequest mLocationSettingsRequest;
public FusedLocationProviderClient mFusedLocationClient;
public LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
public Activity activity;
public Location mLastLocation;
Button button;
TextView latitude,longitude, txt_address;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.activity = this;
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mSettingsClient = LocationServices.getSettingsClient(activity);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mLastLocation = locationResult.getLastLocation();
latitude.setText(String.valueOf(mLastLocation.getLatitude()));
longitude.setText(String.valueOf(mLastLocation.getLongitude()));
new FetchAddressTask().execute(mLastLocation);
stopLocationUpdates();
}
};
button = findViewById(R.id.button);
latitude = findViewById(R.id.latitude);
longitude = findViewById(R.id.longitude);
txt_address = findViewById(R.id.textView4);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fetchLocation();
}
});
}
private void fetchLocation() {
//check if google playservice available
button.setText("Please wait...");
if (isGooglePlayServicesAvailable(this)) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
} else {
startLocationUpdates();
}
}
}
public static boolean isGooglePlayServicesAvailable(Activity activity) {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
if(status != ConnectionResult.SUCCESS) {
if(googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(activity, status, 2404).show();
}
return false;
}
return true;
}
private void startLocationUpdates() {
mSettingsClient
.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(activity, new OnSuccessListener<LocationSettingsResponse>() {
@SuppressLint("MissingPermission")
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
}
})
.addOnFailureListener(activity, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
}
}
});
}
public void stopLocationUpdates() {
mFusedLocationClient
.removeLocationUpdates(mLocationCallback)
.addOnCompleteListener(activity, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
}
});
}
public class FetchAddressTask extends AsyncTask<Location, Void, String> {
private final String TAG = FetchAddressTask.class.getSimpleName();
List<Address> addresses = null;
String resultMessage = "";
public FetchAddressTask() {
}
@Override
protected String doInBackground(Location... locations) {
Geocoder geocoder = new Geocoder(Main2Activity.this,
Locale.getDefault());
Location location = locations[0];
try {
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
// In this sample, get just a single txt_address
1);
if (addresses == null || addresses.size() == 0) {
if (resultMessage.isEmpty()) {
resultMessage = "no txt_address found";
Log.e("debug", resultMessage);
}
} else {
// If an txt_address is found, read it into resultMessage
Address address = addresses.get(0);
ArrayList<String> addressParts = new ArrayList<>();
// Fetch the txt_address lines using getAddressLine,
// join them, and send them to the thread
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
addressParts.add(address.getAddressLine(i));
}
resultMessage = TextUtils.join("\n", addressParts);
}
} catch (IOException ioException) {
// Catch network or other I/O problems
resultMessage = "result not available";
Log.e(TAG, resultMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values
resultMessage = "invalid lat long used";
Log.e("debug", resultMessage + ". " +
"Latitude = " + location.getLatitude() +
", Longitude = " +
location.getLongitude(), illegalArgumentException);
}
return resultMessage;
}
@Override
protected void onPostExecute(String address) {
txt_address.setText(address);
button.setText("Fetch again");
super.onPostExecute(address);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment