在 Xamarin.Android 中需要使用 Activity 通过使用 DependencyService 从 Xamarin.Forms 调用

In Xamarin.Android need use Activity by call from Xamarin.Forms using DependencyService

我在 Xamarin.Forms + Xamarin.Android 中通过手动 https://developers.google.com/pay/api/android/guides/tutorial 实现。我打电话给 Xamarin.Forms:

DependencyService.Get<IPay>().Pay();

在Xamarin.Android我实施

public class Pay_Droid : IPay
{

public void Pay()
{
...
AutoResolveHelper.ResolveTask(
                paymentsClient.LoadPaymentData(request),
                this,
                LOAD_PAYMENT_DATA_REQUEST_CODE);
...
}

}

但在 "this" 中有问题 - 需要使用 activity。如何实施?

正如您在 Xamarin 在 Github, you can just use the "Context 上提供的一些示例中看到的那样,您的应用程序如下在您的 Pay_Droid class 中如下所示:

Context _context;

public Pay_Droid(Context context) : base(context)
{
    _context = context;
}

public void Pay()
{
    ...
    AutoResolveHelper.ResolveTask(paymentsClient.LoadPaymentData(request), _context, LOAD_PAYMENT_DATA_REQUEST_CODE);
    ...
}

首先,您可以在MainActivity class中创建public静态MainActivity,然后在MainActivity OnCreate()方法中将当前MainActivity赋给macvivity:

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

        base.OnCreate(savedInstanceState);


        macvivity = this;

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

最后,您可以 activity 通过 MainActivity.macvivity

public void Pay()
{
...
AutoResolveHelper.ResolveTask(
            paymentsClient.LoadPaymentData(request),
            MainActivity.macvivity,
            LOAD_PAYMENT_DATA_REQUEST_CODE);
...
}

对于 Xamarin,您可以使用:

public void Pay() => AutoResolveHelper.ResolveTask(
                    PaymentsClient.LoadPaymentData(request),
                    Platform.CurrentActivity,
                    LOAD_PAYMENT_DATA_REQUEST_CODE);