I'm trying to request location updates from google play services on my android app. So far I'm able to get last location if i start google maps first, but not able to get any updates.
public class Inbox extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int r = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if(r != 0){
System.out.println(r);
Dialog d = GoogleApiAvailability.getInstance().getErrorDialog(this,r,1);
d.show();
}
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(AppIndex.API).build();
}
mGoogleApiClient.connect();
super.onStart();
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
System.out.println("Problem with rights");
}
else{
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationRequest mLocationRequest = new LocationRequest();
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if(mLastLocation != null){
System.out.println(mLastLocation.toString());
}
else {
System.out.println("No location cached");
}
LocationAvailability a = LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient);
System.out.println(a);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
System.out.println(location.toString());
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
Action viewAction = Action.newAction(...);
AppIndex.AppIndexApi.start(mGoogleApiClient, viewAction);
}
#Override
public void onStop() {
super.onStop();
Action viewAction = Action.newAction(...);
AppIndex.AppIndexApi.end(mGoogleApiClient, viewAction);
mGoogleApiClient.disconnect();
}
}
When i start the app after using google maps, i get the last cached location from:
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
But right after, i print out that location services are unavailable with this:
LocationAvailability a = LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient);
System.out.println(a);
onLocationChanged/onConnectionFailed/onConnectionSuspended are never called.
I'm running my app on a virtual Nexus 6 with android 5.1.0 on Genymotion.
I think you missed a few things here. In you onCennected callback, you have to first check if you can get last known location. If it is not available then you have to request location updates. Refactor your onConnected as shown below and it should work fine
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
System.out.println("Problem with rights");
} else {
Location lastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (lastLocation != null) {
//you have a location. use that here. no need to request for location
// updates
mGoogleApiClient.disconnect();
} else {
//you have to request for location
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(2000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setSmallestDisplacement(50);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
And in your locationChanged callback do the following
#Override
public void onLocationChanged(Location location) {
//now that we got the initial location. it is time to stop the api client
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
// use your newly obtained location here
}
Note : If you try this on GenyMotion. Make sure it can receive location by enabling GPS on the GM emulator
Related
I want to create a database reference in firebase whenever a particular user is online and at the same time store the latitude and longitude of that online user into firebase database by using Geofire. I dont know why my longitude and latitude is returning null even when there is an online user.It's becoming so frustrating as I don't really know what is the issue and I have check so many suggestions from stack overflow and still can't solve it. Your helps will be really appreciated
Here is the code
public class DriversMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
public static final int PERMISSION_FINE_LOCATION = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drivers_maps);
driverSetting = findViewById(R.id.driver_maps_setting);
logoutBtn = findViewById(R.id.driver_maps_logout);
mAuth = FirebaseAuth.getInstance();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
checkLocationPermission();
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(locationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
// if (getApplicationContext()!=null){
if (lastLocation !=null){
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
geoFireDriverAvailability.setLocation(userID,new GeoLocation(location.getLatitude(),location.getLongitude()));
}
}
protected synchronized void buildGoogleApiClient(){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
geoFireDriverAvailability.removeLocation(userID);
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(DriversMapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(DriversMapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
}
}
return true;
}
}
I do need to get the user location continuously; therefore, I use getlastlocation() to get current location of the user. However, it always returns null.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks
,GoogleApiClient.OnConnectionFailedListener{
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
protected double x, y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if(mGoogleApiClient == null){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void onStart(){
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
if(mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle bundle){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
x = mLastLocation.getLatitude();
y = mLastLocation.getLongitude();
}
else{
Log.e("error", "null");
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng gpsLocation = new LatLng(x, y);
mMap.addMarker(new MarkerOptions().position(gpsLocation).title("Here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(gpsLocation));
}
Log.e("error", "null") always executes, meaning getlastlocation() always returns null. In AndroidManifest, I have state enough permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
I searched for similar posts on stackOverflow, and they give some reason (e.g: GPS is not open), but none of them can apply in my cases.
Have you created LocationRequest and requested for location update using requestLocationUpdates?
You need to create LocationRequest like below code.
LocationRequest mLocationRequest;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
And using LocationRequest, you need to call requestLocationUpdates of FusedLocationApi like below code.
protected void startLocationUpdates(){
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest,this);
}
After that you will get location in getlastlocation() method of FusedLocationApi.
Also you should call removeLocationUpdates, when it's not required.
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
My question is how custom it is to isolate certain functionality required by an activity into a hidden fragment, in this case Location Services.
My initial thought was to pass the boilerplate callbacks that are related to Location Services into a separate plain Java utility class, and only keep the listener for onLocationChangedin the Activity. This would be much cleaner.
The problem is that this results in circular dependencies, because the pojo would require a reference to the activity context for certain calls, and the Activity would have a reference to the utility class resulting in a circular dependency, which results in tight coupling.
Therefore my thought was to make a hidden fragment and store the code there; this would keep the code in the main activity clean.
What is the usual way to do this?
The current code that I use:
public class HomeActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener{
private static final String TAG = "HOME_ACTIVITY"; // Logging
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private double mLatCurLoc;
private double mLngCurLoc;
private float MIN_DISTANCE = 200.0f;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onResume(){
super.onResume();
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
#Override
public void onConnected(Bundle bundle) {
// Android Studio complains that we should check the permissions before getting last location
// However, we have already checked permissions in the previous activity
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
} else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setSmallestDisplacement(MIN_DISTANCE)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
#Override
public void onLocationChanged(Location location) {
mLatCurLoc = location.getLatitude();
mLngCurLoc = location.getLongitude();
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Log.i("LOCATION_CHANGED", msg);
}
}
I think that's the beauty of inheritance in OOP. You'd just have an activity which will deal with location services, and make your other activities who want to deal with locations extend e.g. LocationAwareActivity. The moment one of those activities is not interested in locations you'd just change the parent class, and vice versa, the moment one of your activities would like to be aware of locations - it will extend LocationAwareActivity.
For several days I try to modify the program so that each time you press the button addMarkerButton program put the Marker in my new location.
When I turn on the application at once to display me my location without any buttons at all times navigate where currently I am, and when you press the addMarkerButton program put a marker in my new location, when I go to another place, and I press addMarkerButton wants a second marker at a second location but that one did not disappear.
Is it possible? I've tried a lot of combinations, looking for help on the internet and nothing.
My button looks like this (currently only for 2 markers):
addMarkerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
if (tab[0] == null) {
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am");
tab[0] = mMap.addMarker(options);
}
else if (tab [0] != null) {
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am");
tab[1] = mMap.addMarker(options);
In his application I use:
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
so I have:
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) this);
}
else {
handleNewLocation(location) ;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
The method onMapReady() I set mGoogleApiClient.connect()
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mGoogleApiClient.connect();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
method of downloading location:
public void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
and the addition in the method onCreate()
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1 * 1000);
I am trying to add a marker to a current location of my device. Whatever I try, onLocationChanged method triggers once when I starts the app.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private static final String LOG_TAG = "MainActivity";
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
//Initialize Google Play Services
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d(LOG_TAG, "current location " + location.toString());
mLastLocation = location;
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mLastLocation);
markerOptions.title("Test");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[], int... grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
}
You need to remove these statements
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
Once they are gone you should have OnLocatioChanged working continuously.
You may try with OnMyLocationChangeListener like below:
public class MapsActivity extends FragmentActivity implements
OnMyLocationChangeListener {
#Override
public void onMyLocationChange(Location location) {
}
}