android - 一段用于查找当前位置的代码不起作用

android - piece of code used to find current location not working

我在 Android 应用程序中使用以下代码来查找我的移动设备的当前位置:

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Double longitude = location.getLongitude();
Double latitude = location.getLatitude();
Log.i("LATITUDE", latitude.toString());
Log.i("LONGITUTDE", longitude.toString());

到目前为止,它运行良好,并且为我提供了正确的位置坐标。但是不久之前,我的代码没有做任何更改,它开始给我以下错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{di.uoa.gr.e_commerce/di.uoa.gr.e_commerce.FirstResultsActivity}:

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2695) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769) at android.app.ActivityThread.access0(ActivityThread.java:177) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5910) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

我确实打开了我的 WiFi 连接以及我的位置。 任何人都可以找出可能出了什么问题吗?

首先,你应该检查你是否有获取当前位置的权限,如果你是 Android API 23+,你必须手动请求它。

其次,LocationManager.getLastKnownLocation 不一定 return 是一个有效的位置,因为它可能 return "null" 对于您选择的提供者来说没有足够一致的位置( GPS_PROVIDER)。如果这里没有位置,您应该回退到另一个提供商,如果没有找到,请尝试请求一个位置。

getLastKnownLocation
[...] Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

developer.android.com

如果您多次需要该位置,您应该使用其中一种 requestSingleUpdate 方法或 requestLocationUpdates 方法。 Here 是包含上述方法的所有签名的文档。

看起来像这样:

lm.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, null);

然后您会在 class 中收到该位置。但是您 class 需要实施 LocationListener。作为替代方案,您可以提供 LocationListener 作为参数。

这看起来像这样:

lm.requestSingleUpdate(LocationManager.GPS_PROVIDER, new LocationListener() {
    @Override
    public void onLocationChanged(Location location)
    {
        
    }
    
    @Override
    public void onStatusChanged(String s, int i, Bundle bundle)
    {
        
    }
    
    @Override
    public void onProviderEnabled(String s)
    {
        
    }
    
    @Override
    public void onProviderDisabled(String s)
    {
        
    }
    }, null);

然后您会在 onLocationChanged 中获取您的位置。

lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

不一定是 returns 位置,设备没有保存 GPS 位置,因此该方法返回 null;