从Android手机获取GPS数据

从Android手机获取GPS数据,android,gps,Android,Gps,我试着获取gps数据。但gps数据返回空值。当我查看时,下面的“位置”返回空值,因此我无法获取gps数据。 location=locationManager.getLastKnownLocation(locationManager.GPS\U提供程序) 我的代码如下 protected LocationManager locationManager; public GPSTracker(Context context) { this.mContext = context;

我试着获取gps数据。但gps数据返回空值。当我查看时,下面的“位置”返回空值,因此我无法获取gps数据。
location=locationManager.getLastKnownLocation(locationManager.GPS\U提供程序)

我的代码如下

    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();
                        }
                    }
                }
            }

我等待你的帮助。谢谢

您在舱单中设置了这些吗

<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"/>

我像下面的代码一样进行了更改,然后成功地工作了

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();
        }
    }
}

我发现,如果用户有一段时间没有激活/使用位置源,有时函数getLastKnownLocation()会返回null。最好像你那样检查。如果为null,则您必须等待下一个位置更新或设置requestSingleUpdate或RequestLocationUpdate以自己打开GPS。如果提供程序当前已禁用,则返回null。我使用GPS_提供程序。如何启用?