Dev*_*evC 5 c# android xamarin.android xamarin xamarin.forms
我正在尝试使用插件 InAppBilling为 Xamarin 表单解决方案实现(应用程序内计费)我找不到这个插件的任何完整代码示例或文档,除了这个我一步一步按照说明进行操作,但是当我运行我的代码时,我得到这个例外
{System.NullReferenceException: Current Context/Activity is null,确保 MainApplication.cs 文件在您的源代码中设置 CurrentActivity,以便 In App Billing 可以使用它。在 Plugin.InAppBilling.InAppBillingImplementation.get_Context () [0x00000] 在 C:\projects\inappbillingplugin\src\Plugin.InAppBilling.Android\InAppBillingImplementation.cs:59 在 Plugin.InAppBilling.InAppBillingImplements. itemType) [0x00000] in C:\projects\inappbillingplugin\src\Plugin.InAppBilling.Android\InAppBillingImplementation.cs:372 at myproject.MainPage+d__28.MoveNext () [0x00051] in C:\Users\xuser\source\repos \myproject\MainPage.xaml.cs:415 }
我的示例代码
此代码位于(共享/可移植类库/.NET 标准)
主页.xaml.cs
public partial class MainPage : ContentPage
{
void OnPurchased(object sender, EventArgs e)
{
InAppBilling();
}
async void InAppBilling()
{
try
{
var productId = "xxxxx.xxxx_appbilling";
var connected = await CrossInAppBilling.Current.ConnectAsync();
if (!connected)
{
//Couldn't connect to billing, could be offline, alert user
return;
}
//try to purchase item
var purchase = await CrossInAppBilling.Current.PurchaseAsync(productId, ItemType.InAppPurchase, "apppayload");
if (purchase == null)
{
//Not purchased, alert the user
}
else
{
//Purchased, save this information
var id = purchase.Id;
var token = purchase.PurchaseToken;
var state = purchase.State;
}
}
catch (Exception ex)
{
//Something bad has occurred, alert user
}
finally
{
//Disconnect, it is okay if we never connected
await CrossInAppBilling.Current.DisconnectAsync();
}
}
}
Run Code Online (Sandbox Code Playgroud)
以及 Droid Project 中的这段代码
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
InAppBillingImplementation.HandleActivityResult(requestCode, resultCode, data);
}
}
Run Code Online (Sandbox Code Playgroud)
您缺少在OnCreate方法中设置当前活动(上下文)的文档的一部分:
Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity = this;
Run Code Online (Sandbox Code Playgroud)
Android 当前活动设置
该插件使用 Current Activity Plugin 来访问当前的 Android Activity。如果 MainApplication.cs 文件未自动添加到您的应用程序,请务必完成完整设置。请完整阅读当前活动插件文档。您必须至少在 Activity 的 OnCreate 方法中设置以下内容:
| 归档时间: |
|
| 查看次数: |
1244 次 |
| 最近记录: |