从C#代码运行Android Activity(我将Xamarin与Monogame结合使用) [英] Run Android Activity from c# code(I use Xamarin with Monogame)

查看:419
本文介绍了从C#代码运行Android Activity(我将Xamarin与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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆