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();