2014-05-12 24 views
-1

我试图获得我的Android应用程序的位置,但getLastKnownLocation总是返回nullonLocationChanged永远不会被调用。我为我的应用使用以下权限:Android的GPS跟踪问题

ACCESS_NETWORK_STATE, 
ACCESS_FINE_LOCATION ACCESS_COARSE_LOCATION. 

GPS和互联网已打开,在我的设备上。我也尝试了requestLocationUpdates的不同值。

 locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
     locationManager.removeUpdates(this); 

     isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) 
     { 
      // no network provider is enabled 
     } 
     else 
     { 
      hasGPS  = true; 
      location = null; 
      if (isGPSEnabled) 
      { 
       if (location == null) 
       { 
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        if (locationManager != null) 
        { 
         location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) 
         { 
          lat = location.getLatitude(); 
          lng = location.getLongitude(); 
         } 
        } 
       } 
      } 

      if (isNetworkEnabled && location == null) 
      { 
       locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       if (locationManager != null) 
       { 
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) 
        { 
         lat = location.getLatitude(); 
         lng = location.getLongitude(); 
        } 
       } 
      } 
     } 
+0

这可能听起来很傻,但你(即不使用仿真器)上的实际的手机测试正确呢? – jedwards

+0

相关的,可能有助于[这里](http://stackoverflow.com/questions/19621882/getlastknownlocation-returning-null)和[这里](http://stackoverflow.com/questions/1608632/android-locationmanager-getlastknownlocation-返回空)。 – jedwards

+0

是的,我用Android 4.1在平板电脑上试过这段代码。 – user3629312

回答

0

GetLastKnownLocation将返回null,如果它从未有过通过该提供者的位置或位置太旧。所以这并不意外。很可能你没有得到GPS信号,这可能需要几秒钟 - 几分钟(或者在很多建筑物中完全失败)。仔细检查设置中是否打开了GPS,然后查看通知区域中的闪烁圆圈 - 如果它永远不会变得稳定,则说明您没有收到信号。

+0

感谢您的提示,圆圈永远不会变得坚实。我现在会在外面尝试。 – user3629312