2014-08-29 177 views
0

我正在使用android 4.4.2,我试图获取设备位置坐标而没有成功。Android 4.4.2 - 获取设备位置坐标

这是我使用的代码:

private double[] getLastBestLocation() { 
      LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      List<String> providers = lm.getProviders(true); 

      /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/ 
      Location l = null; 

      for (int i=providers.size()-1; i>=0; i--) { 
        l = lm.getLastKnownLocation(providers.get(i)); 
        if (l != null) break; 
      } 

      double[] gps = new double[2]; 
      if (l != null) { 
        gps[0] = l.getLatitude(); 
        gps[1] = l.getLongitude(); 
      } 
      return gps; 
    } 

我试过在SO提供不同的答案:

在清单:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 

在课程,具体为:

How do I get the current GPS location programmatically in Android?
How to get Android GPS location

为重复,因为其他的答案并没有解决我的问题,请不要标记这个问题。

回答

0

该代码使用GPS以及网络来查找位置。

locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 

// getting GPS status 
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

if (isGPSEnabled) { 
    if (location == null) { 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this, null); 
     if (locationManager != null) { 
      location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if (location != null) { 
      latitude = location.getLatitude(); 
      longitude = location.getLongitude(); 

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

if (isNetworkEnabled) { 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this, null); 
    Log.v("Network", "Network is enabled"); 
    if (locationManager != null) { 
     location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
     if (location != null) {       
      latitude = location.getLatitude(); 
      longitude = location.getLongitude(); 
      Log.v("LocationTracker", "Location : "+latitude+", "+longitude); 
     } 
     else 
     { 
       Log.v("LocationTracker", "Location is null"); 
     } 
    } 
    else 
    { 
     Log.v("LocationTracker","Location manager is null"); 
    } 
}