融合位置提供程序似乎不按照设置的间隔更新坐标

时间:2016-06-26 06:28:46

标签: android google-maps-android-api-2

我正在尝试每1秒在textview中更新lat和long值,并且我在Kitkat设备上运行此应用程序。

观察:可以看到位置坐标没有按照间隔进行更新。

“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();
}

}

1 个答案:

答案 0 :(得分:1)

我修复了你的代码。在您使用下面的代码在设备或模拟器上看到预期结果后,请将此答案标记为您的问题的答案。你走了!

您没有私人Location对象来获取您的GoogleApiClientLocationListener对象的最后已知/当前位置。我加了两个。此外,我添加了2个变量,您现在可以使用这些变量来参数化您的位置请求:

        float LOCATION_REFRESH_DISTANCE = 5000;
        long LOCATION_REFRESH_TIME = 0;

请在下面的代码中编辑YOUR_PROJECT bevor testing /使用它。

您的新Java文件:

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();
}
}

您的新(/旧?)XML文件

<?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>

最后但并非最不重要。不要忘记:

您的'compile 'com.google.android.gms:play-services:+'中的

1。 src/build.gradle是这样的:

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。AndroidManifest.xml

中拥有所需的权限

我添加了以下所有权限,但您并不需要全部权限:

<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" />

备注:我专注于根据您的期望和原始代码实施正确的行为。此实现未进行优化。