从Android手机获取GPS数据

时间:2013-03-27 22:23:26

标签: android gps

我尝试获取gps数据。但是gps数据返回null值。当我看,在'location'之后返回null,所以我无法获得gps数据 location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

我的代码正在关注;

    protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager)           mContext.getSystemService(LOCATION_SERVICE);

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

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!isGPSEnabled)
        {

        }
        else if (!isGPSEnabled && !isNetworkEnabled) 
        {
                        } 
        else 
        {
            this.canGetLocation = true;

            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {

                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
我等你的帮忙。感谢

2 个答案:

答案 0 :(得分:1)

您是否在清单中设置了这些?

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

答案 1 :(得分:1)

我改变了如下代码,然后成功地工作了。

String bestProvider = locationManager.getBestProvider(criteria, false);

locationManager.requestLocationUpdates(bestProvider, MIN_TIME_BW_UPDATES,     
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {

location = locationManager.getLastKnownLocation(bestProvider);

  if (location != null) 
   {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}