最近公司需要个GPS 获取手机经纬度的需求,就看了看Unity的官方文档,顺便写个文章,记录一下,但是这个方法有bug,在oppo和魅族的手机上,在禁止使用位置权限后,这个方法就卡死在线程了,不知道为啥,有知道的大神,求解救。
public void GetGps()
{
try
{
//先判断是否打开了定位
if (!Input.location.isEnabledByUser)
{
Debug.LogError("not open GPS");
return;
}
StartCoroutine(GetLocationInfo());
}
catch
{
Debug.LogError("GPS 处理异常");
}
}
private IEnumerator GetLocationInfo()
{
//这里开起定位计算
Input.location.Start();
//时间为20秒
var maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing)
{
yield return new WaitForSeconds(1);
maxWait--;
if (maxWait < 1)
{
Debug.LogError("time out");
yield break;
}
}
if (Input.location.status == LocationServiceStatus.Failed)
{
//无法使用定位
Debug.LogError("can't use GPS ");
yield break;
}
string str = Input.location.lastData.latitude + " " + Input.location.lastData.longitude;
yield return str;
Input.location.Stop();
}
当然了,Android和IOS里面的权限,肯定要自己手动配撒,参考博客:https://blog.csdn.net/yupu56/article/details/78050504