从C#代码运行Android Activity(我将Xamarin与Monogame结合使用) [英] Run Android Activity from c# code(I use Xamarin with Monogame)
问题描述
我将Xamarin与Monogame一起使用,我需要从C#代码运行android活动.我尝试这样做:
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));
}
}
}
然后从Update()中调用Start().
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
推荐答案
现有的Activity
实例在构建时有很多工作要做.通过意图系统启动的活动(所有活动)在实例化时将添加一个Context
引用.此上下文引用在StartActivity
的调用链中使用.
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
.
因此,在Test
活动实例上调用StartActivity
后看到的Java.Lang.NullPointerException
是因为从未设置该实例内的Context
.通过使用new
运算符创建活动实例,您已经绕过了 normal 实例化活动的方式,从而使实例处于无效状态!
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);
这篇关于从C#代码运行Android Activity(我将Xamarin与Monogame结合使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!