【发布时间】:2016-02-03 08:37:51
【问题描述】:
我正在尝试从我的 Android 应用上的 google play 服务请求位置更新。到目前为止,如果我先启动谷歌地图,我可以获得最后一个位置,但无法获得任何更新。
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();
}
}
当我在使用谷歌地图后启动应用程序时,我会从以下位置获取最后缓存的位置:
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
但之后,我打印出位置服务不可用:
LocationAvailability a = LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient);
System.out.println(a);
永远不会调用onLocationChanged/onConnectionFailed/onConnectionSuspended。
我在 Genymotion 上使用 android 5.1.0 的虚拟 Nexus 6 上运行我的应用程序。
【问题讨论】:
标签: java android gps google-play-services