首页 > 解决方案 > GPS定位不起作用

问题描述

我使用此功能查找我的位置。

    public static String getadrr() {
    String adres = "";
    String bestProvider = null;
    Geocoder geocoder = null;
    List<Address> user = null;
    double lati, longi;
    LocationManager lm = (LocationManager) cx.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    bestProvider = lm.getBestProvider(criteria, true);

    if (ActivityCompat.checkSelfPermission(cx, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(cx, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    }
    Location location = lm.getLastKnownLocation(bestProvider);
    if (location == null){
        return "CustomLocation Not found";
    }else{
        geocoder = new Geocoder(cx);
        try {
            user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            lati=(double)user.get(0).getLatitude();
            longi=(double)user.get(0).getLongitude();
            adres =(String)user.get(0).getAddressLine(0);
            Log.e("Data","lat : "+lati);
            Log.e("Data","long : "+longi);
            Log.e("Data","adres : "+adres);

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

    return adres;
}

设备 GPS 已启用,但此功能始终返回“未找到自定义位置”,但当我在手机中运行 Google 地图应用程序时,此功能正常工作。我不明白这个错误的原因。

如何解决?

标签: androidgpslocationmaps

解决方案


getLastKnownLocation 几乎不应该被调用。如果设备已经有一个位置,它只会返回一个结果,而且它通常没有。相反,requestLocationUpdates 或 requestSingleUpdate 并等待回调。


推荐阅读