I was using this same code without problems before but now I'm not able to get the position and the app crashs with the exception bellow. The unique thing that I changed was the way that I'm calling the GetPosition method, before I was calling it by click event and now I have to call it at application starting.
10-19 00:36:47.648 E/mono (10400): Unhandled Exception:
10-19 00:36:47.648 E/mono (10400): System.Threading.Tasks.TaskCanceledException: A task was canceled.
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00026] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at Plugin.Geolocator.GeolocatorImplementation+<GetPositionAsync>d__41.MoveNext () [0x004d3] in <e6cb69436f5b455fa0a66dc46ca4b792>:0 Thread started: <Thread Pool> #18
10-19 00:36:47.648 E/mono (10400): --- End of stack trace from previous location where exception was thrown ---
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0001a] in <43dbbdc147f2482093d8409abb04c233>:0 Thread started: <Thread Pool> #19
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
Thread started: <Thread Pool> #2010-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at BatePapo.MainPage+<GetPosition>d__2.MoveNext () [0x000da] in D:\apps\BatePapo\BatePapo\BatePapo\MainPage.xaml.cs:29
10-19 00:36:47.648 E/mono (10400): --- End of stack trace from previous location where exception was thrown ---
10-19 00:36:47.648 E/mono (10400): at (wrapper dynamic-method) System.Object.75(intptr,intptr)
10-19 00:36:47.678 E/mono-rt (10400): [ERROR] FATAL UNHANDLED EXCEPTION: System.Threading.Tasks.TaskCanceledException: A task was canceled.
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00026] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at Plugin.Geolocator.GeolocatorImplementation+<GetPositionAsync>d__41.MoveNext () [0x004d3] in <e6cb69436f5b455fa0a66dc46ca4b792>:0
10-19 00:36:47.678 E/mono-rt (10400): --- End of stack trace from previous location where exception was thrown ---
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0001a] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at BatePapo.MainPage+<GetPosition>d__2.MoveNext () [0x000da] in D:\apps\BatePapo\BatePapo\BatePapo\MainPage.xaml.cs:29
10-19 00:36:47.678 E/mono-rt (10400): --- End of stack trace from previous location where exception was thrown ---
10-19 00:36:47.678 E/mono-rt (10400): at (wrapper dynamic-method) System.Object.75(intptr,intptr)
10-19 00:36:47.684 D/ (10400): HostConnection::get() New Host Connection established 0xd09ad500, tid 10400
MainActivity.cs:
using System;
using Android;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Content.PM;
using Android.Util;
using Android.Support.V4.App;
using Android.Support.Design.Widget;
using System.Threading.Tasks;
namespace BatePapo.Droid
{
[Activity(Label = "MyApp", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ActivityCompat.IOnRequestPermissionsResultCallback
{
protected async override void OnCreate(Bundle savedInstanceState)
{
await TryToGetPermissions();
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
#region RuntimePermissions
async Task TryToGetPermissions()
{
if ((int)Build.VERSION.SdkInt >= 23)
{
await GetPermissionsAsync();
return;
}
}
const int RequestLocationId = 0;
readonly string[] PermissionsGroupLocation =
{
Manifest.Permission.AccessCoarseLocation,
Manifest.Permission.AccessFineLocation,
};
async Task GetPermissionsAsync()
{
const string permission = Manifest.Permission.AccessFineLocation;
if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
{
//TODO change the message to show the permissions name
Toast.MakeText(this, "Permissões concedidas.", ToastLength.Short).Show();
return;
}
if (ShouldShowRequestPermissionRationale(permission))
{
//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Permissões necessárias");
alert.SetMessage("Esta aplicação precisa de permissões para continuar.");
alert.SetPositiveButton("Conceder permissões", (senderAlert, args) =>
{
RequestPermissions(PermissionsGroupLocation, RequestLocationId);
});
alert.SetNegativeButton("Cancelar", (senderAlert, args) =>
{
Toast.MakeText(this, "Cancelado!", ToastLength.Short).Show();
});
Dialog dialog = alert.Create();
dialog.Show();
return;
}
RequestPermissions(PermissionsGroupLocation, RequestLocationId);
}
public override async void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
switch (requestCode)
{
case RequestLocationId:
{
if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
{
Toast.MakeText(this, "Permissões especiais concedidas.", ToastLength.Short).Show();
}
else
{
//Permission Denied :(
Toast.MakeText(this, "Permissões especiais negadas.", ToastLength.Short).Show();
}
}
break;
}
//base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
#endregion
}
}
MainPage.Xaml.Cs
namespace MyApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : TabbedPage
{
public static Position position;
public MainPage()
{
GetPosition();
InitializeComponent();
}
private async void GetPosition()
{
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
}
catch (Exception)
{
throw;
}
}
}
}
Can anyone see the problem?
GetPosition
is an Asynchronous method, you have to await it and then update the UI. You can't await in a Constructor, so you need to move your logic in to OnAppearing
method
private async Task<Position> GetPositionAsync()
{
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
return await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
}
catch (Exception)
{
// handle it properly
throw;
}
}
}
protected override async void OnAppearing()
{
base.OnAppearing();
var position = await GetPositionAsync();
}
Always use Task<T>
return type for async methods, except for EventHandlers