没有调用android – onConnected()来获取位置更新(GooglePlayApi用于位置)

前端之家收集整理的这篇文章主要介绍了没有调用android – onConnected()来获取位置更新(GooglePlayApi用于位置)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我有这个代码
  1. package com.entu.bocterapp;
  2.  
  3. import android.content.Context;
  4. import android.location.Location;
  5. import android.location.LocationListener;
  6. import android.os.Bundle;
  7. import android.widget.Toast;
  8.  
  9. import com.google.android.gms.common.ConnectionResult;
  10. import com.google.android.gms.common.GooglePlayServicesUtil;
  11. import com.google.android.gms.common.api.GoogleApiClient;
  12. import com.google.android.gms.location.LocationRequest;
  13. import com.google.android.gms.location.LocationServices;
  14.  
  15. public class LocationManager implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
  16.  
  17. private Context mContext;
  18. private GoogleApiClient mGoogleApiClient;
  19. private Location mLastLocation;
  20. private LocationRequest mLocationRequest;
  21.  
  22. public LocationManager(Context context) {
  23. mContext = context;
  24. //
  25. if (checkIfGooglePlayServicesAreAvailable()) {
  26. //Get Access to the google service api
  27. buildGoogleApiClient();
  28. mGoogleApiClient.connect();
  29. } else {
  30. //Use Android Location Services
  31. //TODO:
  32. }
  33. }
  34.  
  35. public Location getCoarseLocation() {
  36. if (mLastLocation != null) {
  37. return mLastLocation;
  38. } else return null;
  39. }
  40.  
  41. private synchronized void buildGoogleApiClient() {
  42. mGoogleApiClient = new GoogleApiClient.Builder(mContext)
  43. .addConnectionCallbacks(this)
  44. .addOnConnectionFailedListener(this)
  45. .addApi(LocationServices.API)
  46. .build();
  47. }
  48.  
  49. private boolean checkIfGooglePlayServicesAreAvailable() {
  50. int errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
  51. if (errorCode != ConnectionResult.SUCCESS) {
  52. GooglePlayServicesUtil.getErrorDialog(errorCode,(RecentSightings) mContext,0).show();
  53. return false;
  54. }
  55. return true;
  56. }
  57.  
  58.  
  59. @Override
  60. public void onConnected(Bundle bundle) {
  61. Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
  62. if (location != null) {
  63. mLastLocation = location;
  64. Toast.makeText(mContext,location.getLongitude() + "," + location.getLatitude() + " : " + location.getAccuracy(),Toast.LENGTH_LONG).show();
  65. }
  66. }
  67.  
  68. @Override
  69. public void onConnectionSuspended(int i) {
  70. Toast.makeText(mContext,"suspended",Toast.LENGTH_LONG).show();
  71. }
  72.  
  73. @Override
  74. public void onConnectionFailed(ConnectionResult connectionResult) {
  75.  
  76. }
  77.  
  78. }

我想在这个类中获取位置,但onConnected()永远不会被调用(我等了1-2分钟).我使用调试器,它说谷歌播放服务可用.

有谁知道我做错了什么?我被困在这里几个小时,阅读一切,无法让它工作.

干杯!

解决方法

你必须打电话
  1. mGoogleApiClient.connect();

猜你在找的Android相关文章