即使启用了 gps 也无法获取位置

cannot get location even gps are enabled

我有一个使用多个位置提供程序来获取最新已知位置信息的功能,但我发现这不稳定(至少在我的 android 7.1 的小米中,我仍然不知道另一个 phone),这是我的函数:

private String getGPS() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = lm.getProviders(false);

    /* 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;
    }

    String msg = "";
    if (l != null) {
        msg = l.getLatitude() + "|" + l.getLongitude();
    }
    return msg;
}

方法 getLastKnownLocation() returns 仅当另一个应用最近请求它时才有效。

你应该这样做:

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

//Avoid the for loop, in this way you can know where there's an issue, if there'll be

Location l = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

if (l== null)
    l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (l== null)
    l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

那么,如果三个都为null,说明在你之前没有应用请求过定位,所以你要自己去请求: 你可以请求"location updates",所以你必须实现一个监听器,如果你想要,你可以将它插入你的activity,这样:

class YourActivity extends Activity() implements LocationListener {

    private Location l;
    private LocationManager lm;

    @Override
    ... onCreate(...) {

        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        l = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

        if (l == null)
            l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (l == null)
            l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (l == null) { //If you need a real-time position, you should request updates even if the first location is not null
            //You don't need to use all three of these, check this answer for a complete explanation:  

            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, 10F, this);
            lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 10 * 1000, 10F, this);
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, 10F, this); //This consumes a lot of battery

            //10 * 1000 is the delay (in millis) between two positions update
            //10F is the minimum distance (in meters) for which you'll have update
        }
    }

    @Override
    void onLocationChanged(Location location) {
        l = location;
    }

    private String getGPS() {
        String msg = "";
        if (l != null) {
            msg = l.getLatitude() + "|" + l.getLongitude();
        }
        return msg;
    }

    //To avoid crash, you must remove the updates in onDestroy():
    @Override
    void onDestroy() {
        lm.removeUpdates(this)
        super.onDestroy()
    }
}

当然你必须插入应用内权限请求 Android 6+