You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Android 8.1(API27)获取位置时出现空引用异常求助

Android 8.1(API 27)定位空引用异常问题排查与修复

问题根源

空引用异常的直接原因是未对Geolocation.GetLastKnownLocationAsync()和Geolocation.GetLocationAsync()的返回值做null判断就直接访问属性,在Android 8.1设备上,以下场景会触发该问题:

  • 设备从未获取过位置数据,GetLastKnownLocationAsync()返回null,直接执行locator.Accuracy = 50时抛出异常;
  • 定位请求超时或设备暂时无法获取位置,GetLocationAsync()返回null,直接执行localNow.Accuracy = 50时抛出异常;
  • 当localNow为null时,直接使用locator的属性,但此时locator也可能为null,进一步触发异常。

修复代码

修改GetCurrentPosition()方法,增加null判断逻辑,确保所有可能为null的对象都被安全处理:

public async Task<Position> GetCurrentPosition()
{
    Position position = new Position(0, 0); // 默认位置
    try
    {
        var request = new GeolocationRequest(GeolocationAccuracy.Best);

        // 先获取最后已知位置,先判断是否为null
        Location locator = await Geolocation.GetLastKnownLocationAsync();
        if (locator != null)
        {
            locator.Accuracy = 50;
        }

        // 获取当前位置,判断是否为null
        Location localNow = await Geolocation.GetLocationAsync(request);
        if (localNow != null)
        {
            localNow.Accuracy = 50;
            position = new Position(localNow.Latitude, localNow.Longitude);
        }
        else
        {
            // 只有当locator不为null时才使用它的位置
            if (locator != null)
            {
                position = new Position(locator.Latitude, locator.Longitude);
            }
            // 否则保持默认位置(0,0)
        }
    }
    catch (FeatureNotSupportedException fnsEx)
    {
        Debug.WriteLine("Feature not supported => " + fnsEx);
    }
    catch (PermissionException pEx)
    {
        Debug.WriteLine("Error => " + pEx);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Unable to get location => " + ex);
    }
    return position;
}

额外注意事项

  • 权限调用顺序:确保在调用GetCurrentPosition()之前,已经通过LocationPermission()方法获取了定位权限,避免因权限问题导致定位失败;
  • 定位超时设置:可以给GeolocationRequest添加超时时间,避免GetLocationAsync()长时间等待,例如:
    var request = new GeolocationRequest(GeolocationAccuracy.Best, TimeSpan.FromSeconds(10));
    

内容的提问来源于stack exchange,提问作者Éder Rocha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:31:23