Android 如何使在Xamarin.Forms项目的另一个类中创建的意图可以访问MainActivity?
我想为Xamarin.forms项目设置通知。将DependencyService用于特定于平台的函数,定义具有这些函数签名的接口 我的界面是:Android 如何使在Xamarin.Forms项目的另一个类中创建的意图可以访问MainActivity?,android,xamarin.forms,xamarin.android,Android,Xamarin.forms,Xamarin.android,我想为Xamarin.forms项目设置通知。将DependencyService用于特定于平台的函数,定义具有这些函数签名的接口 我的界面是: namespace MyProject.Interfaces { public interface ILocalNotificationService { void ShowLocalNotification(string title, string text, string icon); } } 并且,接口实现是: [asse
namespace MyProject.Interfaces
{
public interface ILocalNotificationService
{
void ShowLocalNotification(string title, string text, string icon);
}
}
并且,接口实现是:
[assembly: Dependency(typeof(LocalNotificationService))]
namespace MyProject.Droid.Dependencies
{
public class LocalNotificationService :Activity, ILocalNotificationService
{
private static int notificationId = 1;
public void ShowLocalNotification(string title, string text, string icon)
{
try
{
Intent intent = new Intent(this, typeof(MainActivity));
......
}
catch(Exception ex)
{
}
}
}
}
但是,当我运行程序时,会发生异常:
尝试在空对象引用上调用虚拟方法“java.lang.String android.content.Context.getPackageName()”
此行发生异常:
Intent i = new Intent(this, typeof(AlarmReceiver));
在这种情况下,如何处理此异常以及如何正确获取MainActivity?在表单中,要获取核心
类中应用程序的上下文
,通常我们使用此代码片段
var activity = Forms.Context as Activity;
然后,我们可以将上面的活动
传递到我们希望传递的位置,例如
var activity = Forms.Context as Activity;
Intent i = new Intent(activity, typeof(MainActivity));
不要使用this
尝试使用this.Activity
或Application.Context
@CGPA6.4,谢谢您的回复,我尝试这样添加,但是活动在this
上下文或Application.Context
上下文中都不存在。有什么建议吗?不确定,但是您尝试var activity=Forms.Context作为活动
然后传递活动
。不,这也不起作用。使用它会出现什么错误?这个谎言在活动中起作用,但显示了xamarin表单类中所需的对象引用错误。如何让它工作?你能帮我吗var portInfo=Intent.GetParcelableExtra(EXTRA_标记)作为UsbSerialPortInfo代码>我也不能调用Xamarin.Forms.Context。在命名空间Xamarin.Forms中找不到类型或命名空间名称上下文。