获取当前 Activity Xamarin 表单

Get Current Activity Xamarin forms

我使用 Leadtools SDK for Barcode reader ,当我尝试获取当前 activity 它给了我 null

这是我的代码

   Stream resourceStream = new MemoryStream();
        // Droid.MainActivity activity = Forms.Context as Droid.MainActivity;
        var activity = Android.App.Application.Context as Activity;

        int resId = activity.Resources.GetIdentifier("Datamatrix", "drawable", "com.companyname.UDOSE");
     resourceStream = activity.Resources.OpenRawResource(resId);
     var leadStream = LeadStream.Factory.FromStream(resourceStream);
     await ReadBarcode(leadStream);

activity 总是 null ,我该如何解决这个问题?

1.define一个全局静态Acitivity,在MainActivity:

public static MainActivity Instance;
protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);       
        Instance = this;
        LoadApplication(new App());
    }

当您使用电话时 MainActivity.Instance

2.use当前Activity插件,可以参考Current Activity

var activity = CrossCurrentActivity.Current.Activity;

3.i建议使用DependencyService调用Droid工程中定义的方法,如:

在共享代码中创建接口:

public interface IRead
{
    void Read();
}

然后在Droid项目中创建一个class:

[assembly: Dependency(typeof(AndroidRead))]
namespace Demo.Droid
{
  class AndroidRead:IRead
   {
    public async void Read()
    {
        //here is your codes
        Stream resourceStream = new MemoryStream();
        // Droid.MainActivity activity = Forms.Context as Droid.MainActivity;
        var activity = MainActivity.Instance;

        int resId = activity.Resources.GetIdentifier("Datamatrix", "drawable", "com.companyname.UDOSE");
        resourceStream = activity.Resources.OpenRawResource(resId);
        var leadStream = LeadStream.Factory.FromStream(resourceStream);
        await ReadBarcode(leadStream);
    }
  }
 }

并像 DependencyService.Get<IRead>().Read();

一样调用 page.xmal.cs

在 LEADTOOLS 版本 20 附带的 Xamarin 条形码演示中,activity 是在 MainPage.xaml.cs 中获得的,如下所示:

...
#elif __ANDROID__
   Stream resourceStream = new MemoryStream();
   var activity = Droid.MainActivity.Instance;
...

请使用演示进行测试,并在您身边试用此代码,看看它是否有效。

请记住,电子邮件支持和在线聊天支持服务都是免费的,因此如果您对我们的 SDK 或我们的演示有任何疑问,请随时将其发送至支持@leadtools.com