【发布时间】:2013-12-30 18:31:18
【问题描述】:
我正在开发一个 WinPhone 8 应用程序。 在这个应用程序上有一个按钮“发送短信”。 当用户点击这个按钮时,应该会发生两件事:
- (方法 A)获取当前位置的地理坐标(使用 Geolocator 和 GetGeopositionAsync)。
- (方法 B)编写并发送带有地理坐标的 SMS 作为正文的一部分。
问题:GetGeopositionAsync 是一种异步方法。在检测到坐标之前(需要几秒钟),会发送 SMS(当然没有坐标)。
如何让方法 2 等到坐标可用?
好的,这是我的代码:
当用户按下按钮时,坐标由第一种方法确定,第二种方法发送包含坐标的短信:
private void btnSendSms_Click(object sender, RoutedEventArgs e)
{
GetCurrentCoordinate(); // Method 1
// -> Gets the coordinates
SendSms(); // Method 2
// Sends the coordinates within the body text
}
第一个方法GetCurrentCoordinate()如下所示:
...
private GeoCoordinate MyCoordinate = null;
private ReverseGeocodeQuery MyReverseGeocodeQuery = null;
private double _accuracy = 0.0;
...
private async void GetCurrentCoordinate()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
try
{
Geoposition currentPosition = await geolocator.GetGeopositionAsync(
TimeSpan.FromMinutes(1),
TimeSpan.FromSeconds(10));
lblLatitude.Text = currentPosition.Coordinate.Latitude.ToString("0.000");
lblLongitude.Text = currentPosition.Coordinate.Longitude.ToString("0.000");
_accuracy = currentPosition.Coordinate.Accuracy;
MyCoordinate = new GeoCoordinate(
currentPosition.Coordinate.Latitude,
currentPosition.Coordinate.Longitude);
if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy)
{
MyReverseGeocodeQuery = new ReverseGeocodeQuery();
MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(
MyCoordinate.Latitude,
MyCoordinate.Longitude);
MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted;
MyReverseGeocodeQuery.QueryAsync();
}
}
catch (Exception)
{ // Do something }
}
private void ReverseGeocodeQuery_QueryCompleted(object sender,
QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
lblCurrAddress.Text = address.Street + " " + address.HouseNumber + ",\r" +
address.PostalCode + " " + address.City + ",\r" +
address.Country + " (" + address.CountryCode + ")";
}
}
}
}
以及方法“SendSms()”:
private void SendSms()
{
SmsComposeTask smsComposeTask = new SmsComposeTask();
smsComposeTask.To = "0123456";
smsComposeTask.Body = "Current position: \rLat = " + lblLatitude.Text +
", Long = " + lblLongitude.Text +
"\r" + lblCurrAddress.Text;
// -> The TextBoxes are still empty!
smsComposeTask.Show();
}
问题是,当方法 SendSms() 设置 SmsComposeTask 对象时,所有这些文本框(lblLatitude、lblLongitude、lblCurrAddress)仍然是空的。
我必须确保在 SendSms() 方法开始之前已经设置了 TextBoxes。
【问题讨论】:
-
你应该尝试使用代码自己解决它
标签: c# .net geolocation task-parallel-library async-await