Reputation: 159
I am trying to get user's current location. But in order to do this, I need the Google Play Service to be enabled in my code. So I check the checkPlayService()
method first in my code before I am able to do execute further code such as find the user's current location. My code mostly follows this tutorial.
The issue is that every time my code it returns the Device is not supported.
toast, which may imply that I have not set up Google Play Services correctly in my android studio, or may something be wrong with my code? I know there are many questions on this already but no answer seems to solve it for me, at least for the ones I saw. Please help, I have tried every thing.
I have these lines in my AndroidManifest:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="replaced_my_actual_key_with_this_statement" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
My Dependencies:
compile 'com.google.android.gms:play-services-places:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'
compile 'com.google.android.gms:play-services:11.0.4'
My SDK installations looks like
Code:
public class FindLocation extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks {
private GoogleApiClient mGoogleApiClient;
private TextView selectLocation;
private static final int PERMISSION_REQUEST_TO_ACCESS_LOCATION = 1;
private LocationManager lm;
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Location mLastLocation;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_location);
lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
selectLocation = (TextView) findViewById(R.id.selectLocation);
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
}
getCurrentLocation();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
private void getCurrentLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.i("THIS", "Permission NOT Granted!");
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_REQUEST_TO_ACCESS_LOCATION);
return;
}
Log.i("THIS", "Permission GRANTED!");
isLocationEnabled();
displayLocation();
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_TO_ACCESS_LOCATION: {
Log.i("THIS", "Permission Deciding...");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
Log.i("THIS", "Permission DENIED!");
// Permission denied, boo!
// Disable the functionality that depends on this permission.
}
return;
}
// Add further 'case' lines to check for other permissions this app might request.
}
}
public void isLocationEnabled() {
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Location Service not enabled!");
dialog.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
private boolean checkPlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result, PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
return false;
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return true;
}
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); // ALLOWED
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
selectLocation.setText(latitude + ", " + longitude);
} else {
selectLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.e("THIS", "GoogleApiClient connection failed: " + connectionResult.getErrorMessage());
}
}
Upvotes: 0
Views: 943
Reputation: 159
I have found the solution. It was actually just a silly mistake.
I copied the code from the tutorial I was referring to without realising that there was a slight bug (at least for my application) in the if else statement under the checkPlayServices()
method. The corrected code is shown below.
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
Log.i("THISS", "HII_1");
} else {
Toast.makeText(this, "Device Not Supported", Toast.LENGTH_SHORT).show();
//Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
Upvotes: 0
Reputation: 4520
try this answer.
When ever you want your location . Use below code to retrieve location and show this to your textview
mLocationResolver.resolveLocation(this, new LocationResolver.OnLocationResolved() {
@Override
public void onLocationResolved(Location location) {
// Do what ever you want
textview.setText("latitude : " +location.getLatitude() + ", Longitude : "+ location.getLongitude() + "");
}
});
Upvotes: 1