GPS位置不起作用

时间:2018-07-01 14:30:45

标签: android gps location maps

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

    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,但此功能始终返回“找不到CustomLocation”,但是当我在手机中运行Google Maps应用程序时,此功能可以正常使用。 我不了解此错误的原因。

如何修复?

1 个答案:

答案 0 :(得分:1)

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