简体   繁体   中英

location returns null when started the first time

For my app, I need to get the location of the user, to fetch corresponding data from a server. The problem is that the code I use doesn't properly return the location when it's opened the first time. After restarting the app once it works just fine. I searched the other questions and found out, that if you use getLastKnownLocation and there is no location since the last reboot, it returns null. But why does it work when the app is restarted? Does it fetch it when it's opened the first time, and how can I make it wait until the location is fetched properly at the first opening then?

The code of my MainActivity:

if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {

  requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else {
    progressBar.setVisibility(View.VISIBLE);
    GPSClass gt = new GPSClass(getActivity().getApplicationContext());
    Location location = gt.getLocation();

    if (location == null) {
       //Toast
    } else {
        lat = location.getLatitude();
        lon = location.getLongitude();
    }
    new GetContacts().execute();
}

And the GPSClass:

public class GPSClass implements LocationListener {

Context context;

public GPSClass(Context context) {
    super();
    this.context = context;
}

public Location getLocation(){
    if (ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
        Log.e("fist","error");
        return null;
    }
    try {
        LocationManager lm = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isGPSEnabled){
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,10,this);
            Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            return loc;
        }else{
            Log.e("sec","error");
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}

Here is the full tutorial

I shared a tutorial link follow that link.

Call this below method. It will return value; when lat and long is found. Until object is null or doesn't return any value your app must be idle or show some progress value or tell the user to wait.

InitGeoLocationUpdate.locationInit(SplashScreen.this,
    object -> {
        double latitude = object.latitude;
        double longitude = object.longitude;
        Lg.INSTANCE.d(TAG, "Current Location Latitude: " + latitude + " Longitude: " +
                longitude);
    });

Try this this will not give you null current location

class GetLastLocation extends TimerTask {

LocationManager mlocManager = (LocationManager) 
        getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListenerTmp = new CustomLocationListener();
private final Handler mLocHandler;

public GetLastLocation(Handler mLocHandler) {
    this.mLocHandler = mLocHandler;
}

@Override
public void run() {
    timer.cancel();
    mlocManager.removeUpdates(mlocListenerTmp);
    Location location = mlocManager
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    {
        if (mlocListenerTmp != null) {
            mlocManager.removeUpdates(mlocListenerTmp);
        }
        currentLocation = location;
    }
    if (location != null) {
        String message = String.format(
            "Location \n Longitude: %1$s \n Latitude: %2$s",
            location.getLongitude(), location.getLatitude());
        Log.d("loc", " :" + message);
        Bundle b = new Bundle();
        {
            b.putBoolean("locationRetrieved", true);
            {
                Message msg = Message.obtain();
                {
                    msg.setData(b);
                    mLocHandler.sendMessage(msg);
                }
            }
        }
    } else {
        Log.d(
            "loc",
            ":No GPS or network signal please fill the location manually!");
        location = mlocManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            currentLocation = location;
            Bundle b = new Bundle();
            {
                b.putBoolean("locationRetrieved", true);
                {
                    Message msg = Message.obtain();
                    {
                        msg.setData(b);
                        mLocHandler.sendMessage(msg);
                    }
                }
            }
        } else {
            Bundle b = new Bundle();
            {
                b.putBoolean("locationRetrieved", false);
                {
                    Message msg = Message.obtain();
                    {
                        msg.setData(b);
                        mLocHandler.sendMessage(msg);
                    }
                }
            }
        }
    }
  }
}

call it like this in your MainActivity

timer.schedule(new GetLastLocation(mLocHandler), 3000);

and the customLocationclass is as follows:

public class CustomLocationListener implements LocationListener {

@Override
public void onLocationChanged(Location loc) {
    loc.getLatitude();
    loc.getLongitude();
    currentLocation = loc;
    String Text = "My current location is: " + "Latitud = "
        + loc.getLatitude() + "Longitud = " + loc.getLongitude();
    Log.d("loc", "onLocationChanged" + Text);
}

@Override
public void onProviderDisabled(String provider) {}

@Override
public void onProviderEnabled(String provider) {}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM