我正在尝试连接应用内结算但OnConnected事件未被点击。 我的Android Manifest代码是
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="alphaTestApp.alphaTestApp" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="21" />
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="alphaTestApp" android:icon="@drawable/Icon"></application>
</manifest>
主要活动文件代码为。
[Activity(Label = "alphaTestApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
private InAppBillingServiceConnection _serviceConnection;
string publicKey = "REDACTED";
private IList<Product> _products;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_serviceConnection = new InAppBillingServiceConnection(this, publicKey);
if (_serviceConnection == null)
{
Toast t = Toast.MakeText(this, "Error while connecting", ToastLength.Long);
t.Show();
}
_serviceConnection.Connect();
Toast t1 = Toast.MakeText(this, "Connected app", ToastLength.Long);
t1.Show();
_serviceConnection.OnConnected += () =>
{
Toast t2 = Toast.MakeText(this, "Retrieving Items", ToastLength.Long);
t2.Show();
_products = _serviceConnection.BillingHandler.QueryInventoryAsync(new List<string> {
"goldcoin100"
}, ItemType.Product) as IList<Product>;
if (_products == null)
return;
_serviceConnection.BillingHandler.BuyProduct(_products[0]);
};
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate
{
Toast t3 = Toast.MakeText(this, "Retrieving Items", ToastLength.Long);
t3.Show();
_products = _serviceConnection.BillingHandler.QueryInventoryAsync(new List<string> {
"goldcoin100"
}, ItemType.Product) as IList<Product>;
if (_products == null)
return;
_serviceConnection.BillingHandler.BuyProduct(_products[0]);
};
}
}
答案 0 :(得分:0)
这可能不是原因,但最好在调用OnConnected
之前设置Connect
处理程序,以防它连接的时间少于Toast代码运行所需的时间。
此外,您应该设置OnConnected
处理程序async
,然后等待QueryInventoryAsync
的调用(在Lambda中,async
关键字位于括号之前,例如{ {1}} ...)。事实上,OnConnected += async () =>
将返回QueryInventoryAsync
,因此尝试使用Task<IList<Product>>
进行转换将失败,_products将始终为null。
如果您在模拟器上运行,请确保您已安装Google Play服务并保持最新状态。这里有一篇关于为Xamarin Android播放器执行此操作的文章:Installing Google Play Services in XAP。虽然请注意IList<Product>
不能在使用真实产品的模拟器上运行,但您需要使用测试产品ID(例如BuyProduct
),并注意一旦您购买了此产品ID,您将需要需要先再打ReservedTestProductIDs.Purchased
才能再次购买。)
另外,请勿在开放论坛上发布您的API密钥。