Just a cat
Just a cat

Reputation: 5

GPS location does not work

i use this function for find my location.

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

Device GPS is enabled but this function always returns "CustomLocation Not found" but when i run Google maps app in my phone, this func works healty. I did not understand the cause of this mistake.

How to fix it ?

Upvotes: 0

Views: 93

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93728

getLastKnownLocation should almost never be called. It will only return a result if the device already has a location, and it usually doesn't. Instead, requestLocationUpdates or requestSingleUpdate and wait for the callback.

Upvotes: 1

Related Questions