Run Android Activity from c# code(I use Xamarin with Monogame)

谁说胖子不能爱 提交于 2019-12-11 10:47:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!