Get Current Activity Xamarin forms

4.4k views Asked by At

I used Leadtools SDK for Barcode reader , when i try to get current activity it gives me null

This is my code

   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 always null , how can i solve this ?

2

There are 2 answers

4
Leo Zhu On BEST ANSWER

1.define a global static Acitivity,in 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());
    }

when you use call MainActivity.Instance

2.use the Current Activity Plugin,you could refer to Current Activity

var activity = CrossCurrentActivity.Current.Activity;

3.i suggest you use DependencyService to call the method which was defined in Droid project,like:

create a Interface in sharecode:

public interface IRead
{
    void Read();
}

then in Droid project create a 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);
    }
  }
 }

and call in page.xmal.cs like DependencyService.Get<IRead>().Read();

3
LEADTOOLS Support On

In the Xamarin barcode demo shipped with version 20 of LEADTOOLS, the activity is obtained in MainPage.xaml.cs like this:

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

Please test with the demo and try this code out on your side and see if it is working.

Keep in mind that email support and online chat support services are both free, so if you have any questions related to our SDK or our demos, feel free to send them to [email protected]