首次启动时location返回null

时间:2018-08-19 09:05:00

标签: java android

对于我的应用程序,我需要获取用户的位置,以从服务器获取相应的数据。问题是,我使用的代码在首次打开时无法正确返回该位置。重新启动应用程序后,它就可以正常工作。我搜索了其他问题,发现如果您使用getLastKnownLocation并且自上次重新引导以来没有位置,则它将返回null。但是,为什么在重新启动应用程序后它可以工作?第一次打开时会获取吗?如何让它等到第一次打开时正确获取位置?

我的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();
}

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

2 个答案:

答案 0 :(得分:0)

Here is the full tutorial

我在该链接后分享了一个教程链接。

调用以下方法。它将返回值;当找到经纬度在object为null或不返回任何值之前,您的应用必须处于空闲状态或显示一些进度值或告诉用户等待。

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

答案 1 :(得分:0)

尝试此操作将不会为您提供空的当前位置

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

在您的MainActivity

中这样称呼
timer.schedule(new GetLastLocation(mLocHandler), 3000);

和customLocationclass如下:

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) {}
}