【问题标题】:location returns null when started the first timelocation 第一次启动时返回 null
【发布时间】:2018-08-19 09:05:00
【问题描述】:

对于我的应用,我需要获取用户的位置,以便从服务器获取相应的数据。问题是我使用的代码在第一次打开时没有正确返回位置。重新启动应用程序后,它就可以正常工作了。我搜索了其他问题并发现,如果您使用 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;
}

【问题讨论】:

标签: java android


【解决方案1】:

Here is the full tutorial

我分享了一个教程链接,点击该链接。

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

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

【讨论】:

  • 在另一个类(在 GPSClass 中)中获取位置时,如何在一个类(此处为 MainActivity)中使用此方法?
  • 在任何地方使用此方法。您可以使用它的 onResume 方法。会最好的。在调用该方法之前,请确保您实现了运行时权限。
  • 好的,谢谢。我实际上对 Kotlin 并不熟悉,所以你能告诉我我必须在我的 GPS 类中添加什么,以便我可以在我的活动中调用该函数吗?
  • 这是一个实用类。复制粘贴就行了。我在这里添加的函数,从你的 onrResume 函数中调用它。
  • 好的,谢谢,我试试!添加普通类和实用类有区别吗?
【解决方案2】:

试试这个不会给你空当前位置

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

而customLocation类如下:

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

【讨论】:

  • 谢谢,很有帮助!您认为将class GetLastLocation 用作嵌套类还是单独的类?
  • 我是这么认为的,但是经过几次尝试后,我仍然遇到了一些编译错误。我为 CustomLocationListener 和 GetLastLocation 类创建了一个不同的类。我做了所有缺少的声明,现在在 MainActivity 调用timer.schedule(new GetLastLocation(mLocHandler), 3000); 中说符号无法解析。你能告诉我该怎么做吗?我如何在 MainActivity 中初始化它?
  • 就在错误行之前添加Timer timer = new Timer();
  • 抱歉,我的意思是我的问题是无法解决mLocHandler,而不是计时器!
  • 您是否在项目的AndroidManifest.xml 中添加了GetLastLocation Activity?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 2013-11-18
相关资源
最近更新 更多