Xamarin AndroidRuntimeException “Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag”
In my Android application I’m using the Azure Mobile Services component to connect to Windows Azure.
I want to use the authentication component and let the users login by using their Microsoft account. Here is the code I used:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity : Activity | |
{ | |
int count = 1; | |
public static MobileServiceClient MobileService = new MobileServiceClient( | |
"https://mymobileservice.azure-mobile.net/", | |
"mobileservicekey" | |
); | |
protected override void OnCreate (Bundle bundle) | |
{ | |
base.OnCreate (bundle); | |
// Set our view from the "main" layout resource | |
SetContentView (Resource.Layout.Main); | |
// Get our button from the layout resource, | |
// and attach an event to it | |
Button button = FindViewById<Button> (Resource.Id.myButton); | |
button.Click += async delegate { | |
var user= await MobileService.LoginAsync(this.BaseContext,MobileServiceAuthenticationProvider.MicrosoftAccount); | |
}; | |
} | |
} | |
} | |
However when I try to run this code, it fails the moment the LoginAsync method is called. This is the exception I get:
AndroidRuntimeException “Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag”
I found out that I made a stupid mistake. I was passing the BaseContext instead of the Activity itself. When I updated the code to the following it worked as expected:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity : Activity | |
{ | |
int count = 1; | |
public static MobileServiceClient MobileService = new MobileServiceClient( | |
"https://mymobileservice.azure-mobile.net/", | |
"mobileservicekey" | |
); | |
protected override void OnCreate (Bundle bundle) | |
{ | |
base.OnCreate (bundle); | |
// Set our view from the "main" layout resource | |
SetContentView (Resource.Layout.Main); | |
// Get our button from the layout resource, | |
// and attach an event to it | |
Button button = FindViewById<Button> (Resource.Id.myButton); | |
button.Click += async delegate { | |
var user= await MobileService.LoginAsync(this,MobileServiceAuthenticationProvider.MicrosoftAccount); | |
}; | |
} | |
} | |
} | |