问题
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));
}
}
}
Then from Update() i calling Start().
protected override void Update(GameTime gameTime)
{
...
Test test = new Test();
test.Start();
...
}
But i have error. Help me, please
回答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);
来源:https://stackoverflow.com/questions/31320905/run-android-activity-from-c-sharp-codei-use-xamarin-with-monogame