我尝试使用Google 提供的指南设置InApp 购买以进行捐赠,但是当我调用活动时(无论成功与否都应该返回),但它会引发此错误:
In-app billing error: Illegal state for operation (launchPurchaseFlow): IAB helper is not set up
使用此方法调用活动:
public boolean donation() {
int success = 0;
Intent intent = new Intent(Main.this, Donate.class);
startActivityForResult(intent, success);
if (success != 0) {
return true;
}
else return false;
}
Donate 类(我尝试使用指南进行编码)如下所示:
import java.math.BigInteger;
import java.security.SecureRandom;
import maturaarbeit.nicola_pfister.marks.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
public class Donate extends Activity {
IabHelper mHelper;
private static final String TAG = "Donate";
private String payload;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String base64EncodedPublicKey = getKey();
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
}
});
SharedPreferences prefs = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE); //Add shared preferences
payload = prefs.getString("devpayload", null);
if (payload == null) {
payload = getPayload();
Editor editor = prefs.edit();
editor.putString("devpayload", payload)
.apply();
}
mHelper.launchPurchaseFlow(this, "donation_1chf", 1, mPurchaseFinishedListener, payload);
finish();
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
@Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " +result);
return;
}
else if (info.getDeveloperPayload().equals(payload)) {
return;
}
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
} else {
Log.i(TAG, "onActivityResult handled by IABUtil.");
}
}
private String getKey() {
//Code for building public key
}
private String getPayload() {
SecureRandom random = new SecureRandom();
{
return new BigInteger(130, random).toString(32);
}
}
@Override
protected void onDestroy() {
if (mHelper != null) mHelper.dispose();
mHelper = null;
super.onDestroy();
}
}
如果还没有共享首选项,它应该生成一个存储在共享首选项中的开发负载。如果您需要任何其他信息,请随时询问。
谢谢你的帮助!