ferraro
ferraro

Reputation: 342

Fused location provider doesn't seems to be updating coordinates as per the interval set

I am trying to update lat and long values in a textview for every 1 second,And I am running this app on Kitkat device .

Observation : can see Location coordinates are not getting updated as per the interval.

"MainActivity.java"

public class MapsActivity extends AppCompatActivity implements   GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {

private final String TAG = "ravimaps";

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private TextView lats;
private TextView longs;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    mGoogleApiClient=new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

     lats = (TextView) findViewById(R.id.lat);
      longs= (TextView) findViewById(R.id.Lng);
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest=LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) this);
    }

}

@Override
public void onLocationChanged(Location location)
{
    Log.i(TAG,location.toString());
    lats.setText(Double.toString(location.getLatitude()));
    longs.setText(Double.toString(location.getLongitude()));
    }


    @Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();


}

@Override
protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

}

Upvotes: 2

Views: 1483

Answers (1)

Noureddine Ouertani
Noureddine Ouertani

Reputation: 324

I fixed your code. Please mark this answer as the answer to your question after you see your expected result on your device or emulator with the code below. Here you go!

You had no private Location object for getting the last known / current location with your GoogleApiClient and no LocationListener object for asking for it. I added both. Moreover I added 2 variables that you can use now to parametrize your requests for locations:

        float LOCATION_REFRESH_DISTANCE = 5000;
        long LOCATION_REFRESH_TIME = 0;

Please edit YOUR_PROJECT in the code below bevor testing/using it.

Your new Java file:

package YOUR_PROJECT;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

private final String TAG = "ravimaps";
private LocationManager locationManager;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private TextView lats;
private TextView longs;
private Location mLastLocation;
LatLng newPosition;

LocationListener mlocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        mLastLocation=location;

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    lats = (TextView) findViewById(R.id.lat);
    longs = (TextView) findViewById(R.id.Lng);
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        float LOCATION_REFRESH_DISTANCE = 5000;
        long LOCATION_REFRESH_TIME = 0;
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, mlocationListener);
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLastLocation!=null){
            Toast.makeText(getApplicationContext(), "YES! mLastLocation!=null", Toast.LENGTH_SHORT).show();
            Log.i(TAG, mLastLocation.toString());
            lats.setText(Double.toString(mLastLocation.getLatitude()));
            longs.setText(Double.toString(mLastLocation.getLongitude()));
            double latitude = mLastLocation.getLatitude();  //Save latitude in a double variable
            double longitude = mLastLocation.getLongitude(); //Save longitude in a double variable
            //Toast to display Coordinates
            Toast.makeText(getApplicationContext(), "Latitude = " + latitude + "\nLongitude = " + longitude, Toast.LENGTH_SHORT).show();

        }
    }

}


@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}


@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();

}

@Override
protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}
}

Your new (/old?) XML file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="YOUR_PROJECT.MainActivity">


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/lat"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="47dp"
    android:layout_marginStart="47dp"
    android:layout_marginTop="171dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/Lng"
    android:layout_centerVertical="true" />
</RelativeLayout>

Last but not least. Do not forget to:

1. 'compile 'com.google.android.gms:play-services:+' in your src/build.gradle like this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services:+'
}

2. to have the needed permissions in your AndroidManifest.xml

I added all the following permissions but you don't need all of them:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MOCK_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Remark: I focused on implementing the correct behaviour based on your expectation and your original code. This implementation is not optimized.

Upvotes: 1

Related Questions