I'm asking about receiving FINE and COARSE permissions successfully. Then building GoogleAPIClient
and creating LocationRequest
but then FusedLocationApi.getLastLocation
it keeps on returning null. I am aware that the connection should be established before asking for a location. Because onStart()
where the Connection is established is called after retrieveLocation()
method I call mLocationApiClient.connect()
immediately after building GoogleApiClient. onConnected
method is being hit and when I check mLocationApiClient.isConnected() it says 'true'. And then when I try to retrieve LastLocation
using FusedLocationApi
it always return null. I feel confused because I've checked multiple times and there is a connection but no location retrieved. Where am I wrong?
MainActivity:
@EActivity(R.layout.activity_main)
public class MainActivity
extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int MY_PERMISSION_REQUEST_CODE = 7171;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 7172;
private static int UPDATE_INTERVAL = 5000; // seconds
private static int FATEST_INTERVAL = 3000; // seconds
private static int DISPLACEMENT = 10; // meters
private LocationRequest mLocatiionRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
@AfterViews
void retrieveLocation() {
int fineLocationPermission =
checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
int coarseLocationPermission =
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
if (fineLocationPermission != PackageManager.PERMISSION_GRANTED
&& coarseLocationPermission != PackageManager.PERMISSION_GRANTED) {
this.requestPermissions(
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_REQUEST_CODE
);
} else {
if (this.isPlayServiceAvailable()) {
this.buildGoogleApiClient();
this.createLocationRequest();
this.mLastLocation = LocationServices.FusedLocationApi.getLastLocation(this.mGoogleApiClient);
String message = "";
if (this.mLastLocation != null)
message = "Lat: " + this.mLastLocation.getLatitude() + ", Lon: " + this.mLastLocation.getLongitude();
else
message = "Didn't manage to get location.";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (this.isPlayServiceAvailable())
this.buildGoogleApiClient();
}
break;
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
this.retrieveLocation();
}
@Override
public void onConnectionSuspended(int i) {
this.mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
this.mLastLocation = location;
}
@Override
protected void onStart() {
super.onStart();
if (this.mGoogleApiClient != null)
this.mGoogleApiClient.connect();
}
@Override
protected void onStop() {
LocationServices.FusedLocationApi.removeLocationUpdates(this.mGoogleApiClient, this);
if (this.mGoogleApiClient != null)
this.mGoogleApiClient.disconnect();
super.onStop();
}
private boolean isPlayServiceAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(), "The device is not supported", Toast.LENGTH_LONG).show();
finish();
}
return false;
}
return true;
}
private void buildGoogleApiClient() {
if (this.mGoogleApiClient == null) // avoid recreating client when it is already connected
this.mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
if (!this.mGoogleApiClient.isConnected()) // avoid unwanted hitting of onConnect callback
this.mGoogleApiClient.connect();
}
private void createLocationRequest() {
this.mLocatiionRequest = new LocationRequest();
this.mLocatiionRequest.setInterval(this.UPDATE_INTERVAL);
this.mLocatiionRequest.setFastestInterval(this.FATEST_INTERVAL);
this.mLocatiionRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
this.mLocatiionRequest.setSmallestDisplacement(this.DISPLACEMENT);
}
private void startLocationUpdates() {
int fineLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
int coarseLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
if (fineLocationPermission != PackageManager.PERMISSION_GRANTED && coarseLocationPermission != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient, this.mLocatiionRequest, this);
}
private void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(this.mGoogleApiClient, this);
}
}
Build.graddle:
apply plugin: 'com.android.application'
apply plugin: 'android-apt'
def AAVersion = '4.3.1'
apt {
arguments {
androidManifestFile variant.outputs[0]?.processResources?.manifestFile
resourcePackageName 'com.mosy.kalin.mosy'
}
}
android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
applicationId "mosy.mosyandroid"
minSdkVersion 26
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
exclude group: 'com.android.support', module: 'support-annotations'
})
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
compile 'com.android.support:appcompat-v7:26.0.0-beta2'
compile 'com.android.support:design:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:support-v4:26.0.0-beta2'
compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.google.android.gms:play-services-location:11.0.4'
testCompile 'junit:junit:4.12'
}
2 Reson for this
So for avoid this you have to fetch location from GPS also, consider following code
add this dependencies in your build gradle
Add this Class for getting location -- LocationResolver.java
In your activity follow these step
Create and initialize LocationResolver variable
And also add these lines into your activity
Usage: When ever you want location use this code for getting location