Skip to content Skip to sidebar Skip to footer

Run Android Activity From C# Code(i Use Xamarin With Monogame)

I use Xamarin with Monogame and i need run android activity from c# code. I try do this: public class Test : Activity { public void Start() { StartActivity(typeof(MyActivity));

Solution 1:

An existing Activity instance has a bit of work that goes on behind the scenes when it's constructed; activities started through the intent system (all activities) will have a Context reference added to them when they are instantiated. This context reference is used in the call-chain of StartActivity.

So, the Java.Lang.NullPointerException seen after invoking StartActivity on your Test activity instance is because the Context inside that instance has never been set. By using the new operator to create an activity instance you've circumvented the normal way activities are instantiated, leaving your instance in an invalid state!

This can be fixed by using the global application context to launch the activity:

var intent = new Intent(Android.App.Application.Context, typeof(Test));
intent.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity (intent);

Post a Comment for "Run Android Activity From C# Code(i Use Xamarin With Monogame)"