FusedLocationApi.requestLocationUpdates - onLocationChanged未被调用

时间:2016-12-30 16:28:34

标签: android google-api-client android-location fusedlocationproviderapi android-fusedlocation

我一直试图在我的Android应用程序中获取设备的当前位置(不是不断更新)。我使用的是GoogleApiClient。由于该位置始终返回null - 我读到使用FusedLocationApi.requestLocationUpdates可能会修复它。所以我做到了。

现在它也没有用。这是我的代码。如果有人告诉我该怎么做,我真的很有责任。

先谢谢!

    package com.example.root.restaurant;
    import android.Manifest;
    import android.annotation.TargetApi;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Build;
    import android.provider.ContactsContract;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.annotation.RequiresApi;
    import android.support.v4.app.ActivityCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.RelativeLayout;
    import android.widget.Button;
    import android.graphics.Color;
    import android.widget.EditText;
    import android.view.View;
    import android.widget.TextView;
    import android.content.Intent;
    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.FusedLocationProviderApi;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;

    import org.w3c.dom.Text;

    import java.util.List;

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

        private static GoogleApiClient googleApiClient;
        private Location mLastLocation;
        TextView t;
        private Double myLatitude;
        private Double myLongitude;
        private LocationRequest locationRequest;
        private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.i("jennysMsg", "..............................Started");

    t = (TextView) findViewById(R.id.textView2);

    locationRequest = new LocationRequest();
    locationRequest.setInterval(15 * 1000);
    locationRequest.setFastestInterval(15 * 1000);
    locationRequest.setSmallestDisplacement(0);
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);


    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .setAccountName("kfoozminus")
            .build();
    if (googleApiClient != null) {
        Log.i("jennysMsg", ".....................................it's not nul!!!");
        googleApiClient.connect();
    }
}

@Override
public void onConnected(@Nullable 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) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    if (location == null) {
        requestLocationUpdates();
    }
    else {
        myLatitude = location.getLatitude();
        myLongitude = location.getLongitude();
        t.setText("Location : " + String.valueOf(myLatitude) + String.valueOf(myLongitude));
    }
}

private void requestLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        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) {

    myLatitude = location.getLatitude();
    myLongitude = location.getLongitude();
    t.setText("Location : " + String.valueOf(myLatitude) + String.valueOf(myLongitude));

}

@Override
protected void onStart() {
    super.onStart();
    //googleApiClient.connect();
}

@Override
protected void onResume() {
    super.onResume();
    if(googleApiClient.isConnected()) {
        requestLocationUpdates();
    }
}

@Override
protected void onPause() {
    super.onResume();
    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}

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

1 个答案:

答案 0 :(得分:0)

首先,您需要检查是否在清单中添加了权限。如果您需要大致位置,请ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION以获得准确位置。

其次你的代码对我来说似乎不错,除非你需要从你的onStart方法取消注释googleApiClient.connect()。

如果您使用模拟器,它无法向您返回位置,而是您需要在模拟器旁边创建自定义位置(经度,纬度),点击设置/更多图标,您将能够找到经度和纬度,手动设置经度和纬度,点击发送,你应该好好去。如果您仍然无法工作,可以尝试重新启动模拟器,也可以使用真实设备测试此代码。

更新: 请检查您的模拟器是否包含Google软件包,如果您在尝试访问google play servide时未包含Google软件包,则它将始终在您的Google Play服务中返回null