0

我正在开发基于小型位置的 android 应用程序,其中我需要用户当前位置。一旦位置发生一些变化,我也会更新用户当前位置。我的代码如下所示:

private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);

}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
}; 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LocationManager locationManager;
    String svcName = Context.LOCATION_SERVICE;
    locationManager = (LocationManager)getSystemService(svcName);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);
    String provider = locationManager.getBestProvider(criteria, true);

    //Location l = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
    Location l = locationManager.getLastKnownLocation(provider);

    updateWithNewLocation(l);

    locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);

}


private void updateWithNewLocation(Location location) 
{
    TextView myLocationText;
    myLocationText = (TextView)findViewById(R.id.myLocationText);
    String latLongString = "No location found";
    if (location != null) {
    double lat = location.getLatitude();
    double lng = location.getLongitude();
    latLongString = "Lat:" + lat + "\nLong:" + lng;
    }
myLocationText.setText("Your Current Position is:\n" +
latLongString);

}

我的问题是,当我使用提供商作为网络时,它工作正常。但是当它选择 gps 作为提供者时,它会给出空值。我第一次知道它给了我空值。我也使用了 onLocationChanged 方法,但它仍然没有给我正确的输出。当我打开我的应用程序时,它会显示输出空值,它还会启动 gps 来搜索我的位置。我等待一段时间来获取更新的位置,但它没有给我有效的输出。我的代码有什么问题吗。我正在使用安卓设备。

需要帮助...谢谢...

4

5 回答 5

0

更改此行

Location l = locationManager.getLastKnownLocation(provider); 
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);

Location l = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 2000, 10, locationListener);

然后我认为它会起作用。

或者您可以按照教程使用 gps 获取位置

于 2013-01-02T09:32:00.880 回答
0

当您将提供商用作网络时,您会立即获得位置,因为它会获取网络提供商最近的塔的位置值。但是当您使用 GPS 时,获取当前位置值需要一些时间。在您的情况下(在查看代码之后),很明显您正在使用网络提供商获取最后一个已知位置,因此它可以获取位置,并且在使用 gps 提供商时需要一些时间,更重要的是,如果您在附近区域,则需要更多时间通过 gps 提供程序获取位置值。

于 2013-01-02T09:37:36.567 回答
0

请在使用用户当前位置时使用此类

private GPSTracker gps;

gps = new GPSTracker(this);

if (gps.canGetLocation()) {


        /*----get Lat and Long---------*/

        double lat = gps.getLatitude();
        double lon = gps.getLongitude();

        String mLatitute = Double.toString(lat);
        String mLongitute = Double.toString(lon);
}

GPTTracker 服务:

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location = null; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
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 && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.e("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.e("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog
            .setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    // Showing Alert Message
    alertDialog.show();
}

public void onLocationChanged(Location location) {
}

public void onProviderDisabled(String provider) {
}

public void onProviderEnabled(String provider) {
}

public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}
}
于 2013-01-02T09:53:53.483 回答
0

您是否在清单中输入了这些权限?

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_GPS"/>
于 2013-01-02T09:35:53.153 回答
0

在这里,系统正在尝试根据您设置的标准选择最佳提供商

e.g. criteria.setPowerRequirement(Criteria.POWER_LOW);

但 GPS 提供商不符合您指定的标准。这就是它可能无法正常工作的原因。要么更改标准,要么如果您只想从 GPS 提供商获取位置更新,请使用以下代码,

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000, 10, locationListener);
于 2013-01-02T09:39:59.417 回答