当我的蓝牙设备断开连接时,我尝试获取我的位置,但总是需要很长时间。
[BroadcastReceiver]
[IntentFilter(new[] { BluetoothDevice.ActionAclDisconnected })]
public class BluetoothReceiver : BroadcastReceiver
{
public async override void OnReceive(Context context, Intent intent)
{
Log2("On bluetooth receive");
Log2("Intent is: " + intent.Action);
if (BluetoothDevice.ActionAclDisconnected.Equals(intent.Action))
{
BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
string deviceName = device.Name;
Log2("Device name is: " + deviceName);
if (device.Name.ToUpper().IndexOf("FOO") != -1)
{
Log2("Getting location");
var loc = await GetLocation();
if (loc == null || loc.HasValue == false)
{
Log2("Location is null or does not have value");
return;
}
Log2("Location is: " + JsonConvert.SerializeObject(loc.Value));
}
}
}
}
static Location latestLocation = null;
private async static Task<(double lat, double lon)?> GetLocation()
{
LocationManager locationManager = (LocationManager)_this.GetSystemService(LocationService);
string provider = LocationManager.NetworkProvider;
if (locationManager.IsProviderEnabled(provider) == false)
{
Log2("Provider: " + provider + " was not available");
provider = LocationManager.GpsProvider;
if (locationManager.IsProviderEnabled(provider) == false)
{
Log2("Provider: " + provider + " was not available");
provider = locationManager.GetBestProvider(new Criteria(), true);
if (provider == null)
{
Log2("Best provider was not available, returning");
return null;
}
}
}
Log2("Requested location update and waiting");
latestLocation = null;
locationManager.RequestLocationUpdates(provider, 30000, 1, _this);
Stopwatch sw = new Stopwatch();
sw.Start();
while (latestLocation == null && sw.ElapsedMilliseconds < 30000)
await Task.Delay(100);
if (latestLocation == null)
{
Log2("Latest location was null, returning");
return null;
}
double latitude = latestLocation.Latitude;
double longitude = latestLocation.Longitude;
return (latitude, longitude);
}
public void OnLocationChanged(Location location)
{
Log2("location changed event.");
latestLocation = location;
Log2($"Latitude: {location.Latitude}, Longitude: {location.Longitude}");
}
当我检查日志时。 OnLocationChanged 需要超过 8 分钟才能触发。它使用 NetworkProvider,但我也使用 GPS 提供商对其进行了测试。 当我把车停在家里并且我的手机与汽车的蓝牙断开连接时,它就出现了这个问题。在家用蓝牙耳机测试时似乎没有这个问题。 这是日志文件:
[2/21/2024 5:24 PM 22674ms] On bluetooth receive
[2/21/2024 5:24 PM 0019ms] Intent is: android.bluetooth.device.action.ACL_DISCONNECTED
[2/21/2024 5:24 PM 0026ms] Device name is: FOO
[2/21/2024 5:24 PM 0021ms] Getting location
[2/21/2024 5:24 PM 0034ms] Requested location update and waiting
[2/21/2024 5:25 PM 42009ms] Latest location was null, returning
[2/21/2024 5:25 PM 0048ms] Location is null or does not have value
[2/21/2024 5:33 PM 507948ms] location changed event.
[2/21/2024 5:33 PM 0015ms] Latitude: 123.2584486, Longitude: 456.1175657
如何才能在 10 秒内获取位置?
问题是我只将 GPS 权限设置为“使用应用程序时”,而不是一直设置。因此,如果我切换到另一个应用程序或关闭屏幕,它就会无限期地挂起。