Skip to content

Instantly share code, notes, and snippets.

@Redman1037
Last active November 7, 2017 10:17
Show Gist options
  • Save Redman1037/3f4cc1e15378d68b484a9cc8ac03132f to your computer and use it in GitHub Desktop.
Save Redman1037/3f4cc1e15378d68b484a9cc8ac03132f to your computer and use it in GitHub Desktop.
Location
package in.eightfolds.eemagic.EEMagic.activity;
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import in.eightfolds.eemagic.EEMagic.adapter.SelectLocationAdapter;
import in.eightfolds.eemagic.EEMagic.dto.City;
import in.eightfolds.eemagic.EEMagic.utils.Constants;
import in.eightfolds.eemagic.R;
import in.eightfolds.eemagic.rest.EightfoldsVolley;
import in.eightfolds.eemagic.rest.VolleyResultCallBack;
import in.eightfolds.eemagic.utils.EightfoldsUtils;
/**
* Created by Manohar on 11/3/2017.
*/
public class SelectLocationActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
ResultCallback<LocationSettingsResult> {
String cityByUserLocation = "";
protected static final String TAG = "SelectLocation";
//Any random number you can take
public static final int REQUEST_PERMISSION_LOCATION = 10;
/**
* Constant used in the location settings dialog.
*/
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
/**
* The desired interval for location updates. Inexact. Updates may be more or less frequent.
*/
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
/**
* The fastest rate for active location updates. Exact. Updates will never be more frequent
* than this value.
*/
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
// Keys for storing activity state in the Bundle.
protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates";
protected final static String KEY_LOCATION = "location";
protected final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string";
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Stores parameters for requests to the FusedLocationProviderApi.
*/
protected LocationRequest mLocationRequest;
/**
* Stores the types of location services the client is interested in using. Used for checking
* settings to determine if the device has optimal location settings.
*/
protected LocationSettingsRequest mLocationSettingsRequest;
/**
* Represents a geographical location.
*/
protected Location mCurrentLocation;
/**
* Tracks the status of the location updates request. Value changes when the user presses the
* Start Updates and Stop Updates buttons.
*/
protected Boolean mRequestingLocationUpdates;
/**
* Time when the location was updated represented as a String.
*/
protected String mLastUpdateTime;
int RQS_GooglePlayServices = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_location);
initUiComponents();
}
/**
* This method is to initialize all View ids,variable,Onclicklisteners
*
* @author : manohar
*/
private void initUiComponents() {
locationrequests();
}
private void locationrequests() {
mRequestingLocationUpdates = false;
buildGoogleApiClient();
createLocationRequest();
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
//step 2
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
//step 3
protected void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
//step 4
protected void checkLocationSettings() {
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
mLocationSettingsRequest
);
result.setResultCallback(this);
}
/**
* Requests location updates from the FusedLocationApi.
*/
protected void startLocationUpdates() {
if (checkLocationPermission()) {
goAndDetectLocation();
}
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location")
.setMessage("We need you to grant Location permission to get your city")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(SelectLocationActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_LOCATION);
}
return false;
} else {
return true;
}
}
public void goAndDetectLocation() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
mLocationRequest,
this
).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
mRequestingLocationUpdates = true;
// setButtonsEnabledState();
}
});
}
/**
* Removes location updates from the FusedLocationApi.
*/
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient,
this
).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
mRequestingLocationUpdates = false;
// setButtonsEnabledState();
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSION_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
goAndDetectLocation();
}
break;
}
}
private void updateCityAndPincode(double latitude, double longitude) {
try {
Geocoder gcd = new Geocoder(SelectLocationActivity.this, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
cityByUserLocation = addresses.get(0).getLocality();
// if (TextUtils.isEmpty(searchView.getQuery())) {
// searchView.setQuery(cityByUserLocation, false);
// }
// System.out.println(addresses.get(0).getLocality());
}
} catch (Exception e) {
Log.e(TAG, "exception:" + e.toString());
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_close:
finish();
break;
case R.id.linear_use_my_location:
//If
if (TextUtils.isEmpty(cityByUserLocation)) {
if (mGoogleApiClient.isConnected()) {
buildLocationSettingsRequest();
checkLocationSettings();
}
} else {
EightfoldsUtils.getInstance().saveToSharedPreference(this, Constants.CITY, cityByUserLocation);
if (userType == Constants.USER_TYPE_SERVICE_PROVIDER) {
Intent intent = new Intent(this, ServiceProvidersHomeActivity.class);
startActivity(intent);
finish();
} else if (userType == Constants.USER_TYPE_HIRER) {
Intent intent = new Intent(this, HirersHomeActivity.class);
startActivity(intent);
finish();
}
}
break;
}
}
@Override
protected void onStart() {
super.onStart();
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int resultCode = googleAPI.isGooglePlayServicesAvailable(this);
if (resultCode == ConnectionResult.SUCCESS) {
mGoogleApiClient.connect();
} else {
googleAPI.getErrorDialog(this, resultCode, RQS_GooglePlayServices);
}
}
@Override
protected void onResume() {
super.onResume();
// Within {@code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
// Toast.makeText(FusedLocationWithSettingsDialog.this, "location was already on so detecting location now", Toast.LENGTH_SHORT).show();
startLocationUpdates();
}
}
@Override
protected void onPause() {
super.onPause();
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
@Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "User agreed to make required location settings changes.");
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Log.i(TAG, "User chose not to make required location settings changes.");
break;
}
break;
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mCurrentLocation != null)
updateCityAndPincode(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
else {
Log.i(TAG, "GoogleApiClient connected");
// LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
// .addLocationRequest(new LocationRequest().setPriority(LocationRequest.PRIORITY_LOW_POWER));
//
// PendingResult<LocationSettingsResult> result =
// LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
//
// result.setResultCallback(this);
buildLocationSettingsRequest();
checkLocationSettings();
}
}
}
@Override
public void onConnectionSuspended(int i) {
Log.i("onConnectionSuspended", "" + i);
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
@Override
public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "All location settings are satisfied.");
startLocationUpdates();
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().
Toast.makeText(SelectLocationActivity.this, "Please turn on location", Toast.LENGTH_SHORT).show();
//
//move to step 6 in onActivityResult to check what action user has taken on settings dialog
status.startResolutionForResult(SelectLocationActivity.this, REQUEST_CHECK_SETTINGS);
} 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;
}
}
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
stopLocationUpdates();
updateCityAndPincode(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment