0

我使用 Leadtools SDK for Barcode reader ,当我尝试获取当前活动时,它给了我 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);

活动始终为空,我该如何解决?

4

2 回答 2

2

1.定义一个全局静态活动,在 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.使用当前活动插件,可以参考当前活动

var activity = CrossCurrentActivity.Current.Activity;

3.我建议你使用DependencyService来调用在Droid项目中定义的方法,比如:

在共享代码中创建一个接口:

public interface IRead
{
    void Read();
}

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

[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);
    }
  }
 }

并调用 page.xmal.cs 之类的DependencyService.Get<IRead>().Read();

于 2019-06-25T01:44:37.507 回答
0

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

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

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

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

于 2019-06-25T14:21:17.107 回答