Android In App Purchase

时间:2015-08-18 16:39:53

标签: java android in-app-purchase

我创建了一个Android应用,它有两个活动,一个是免费广告,另一个是广告。我想在应用内购买广告来删除广告,因此当用户购买应用时,它会向他显示无广告活动,如果没有,则会显示他的广告活动。有人可以告诉我该怎么做。这是我的代码。

import cf.droiddev.androidtutorials.util.IabHelper;
import cf.droiddev.androidtutorials.util.IabResult;
import cf.droiddev.androidtutorials.util.Inventory;
import cf.droiddev.androidtutorials.util.Purchase;

public class RemoveAdsActivity extends Activity {

static final String TAG = "Android Tutorials";

static final String SKU_INAPPITEM = "android.test.purchased"; //"change to your in app item"; // "android.test.cancelled";

String base64EncodedPublicKey = "REPLACE WITH YOUR PUBLIC KEY";

// The helper object
IabHelper mHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.remove_ads_activity);

    mHelper = new IabHelper(this, base64EncodedPublicKey);

    // enable debug logging (for a production application, you should set
    // this to false).
    mHelper.enableDebugLogging(true);

    // Start setup. This is asynchronous and the specified listener
    // will be called once setup completes.
    Log.d(TAG, "Starting setup.");
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        @Override
        public void onIabSetupFinished(IabResult result) {
            Log.d(TAG, "Setup finished.");

            if (!result.isSuccess()) {
                // Oh noes, there was a problem.
                complain("Problem setting up in-app billing: " + result);
                return;
            }

            // Hooray, IAB is fully set up. Now, let's get an inventory of
            // stuff we own.
            Log.d(TAG, "Setup successful. Querying inventory.");
            mHelper.queryInventoryAsync(mGotInventoryListener);
        }
    });

}

// Listener that's called when we finish querying the items and
// subscriptions we own
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
    @Override
    public void onQueryInventoryFinished(IabResult result,
            Inventory inventory) {
        Log.d(TAG, "Query inventory finished.");
        if (result.isFailure()) {
            complain("Failed to query inventory: " + result);
            return;
        }

        Log.d(TAG, "Query inventory was successful.");

        /*
         * Check for items we own. Notice that for each purchase, we check
         * the developer payload to see if it's correct! See
         * verifyDeveloperPayload().
         */

        // Check for gas delivery -- if we own gas, we should fill up the
        // tank immediately
        Purchase removeAdsPurchase = inventory.getPurchase(SKU_INAPPITEM);
        if (removeAdsPurchase != null
                && verifyDeveloperPayload(removeAdsPurchase)) {
            Log.d(TAG, "User has already purchased this item for removing ads. Write the Logic for removign Ads.");
            mHelper.consumeAsync(inventory.getPurchase(SKU_INAPPITEM),
                    mConsumeFinishedListener);
            return;
        }

        Log.d(TAG, "Initial inventory query finished; enabling main UI.");
    }

};

// User clicked the "Buy Gas" button
public void onBuyGasButtonClicked(View arg0) {
    Log.d(TAG, "Buy gas button clicked.");

    /*
     * TODO: for security, generate your payload here for verification. See
     * the comments on verifyDeveloperPayload() for more info. Since this is
     * a SAMPLE, we just use an empty string, but on a production app you
     * should carefully generate this.
     */
    String payload = "";

    mHelper.launchPurchaseFlow(this, SKU_INAPPITEM, 10000,
            mPurchaseFinishedListener, payload);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + ","
            + data);

    // Pass on the activity result to the helper for handling
    if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
        // not handled, so handle it ourselves (here's where you'd
        // perform any handling of activity results not related to in-app
        // billing...
        super.onActivityResult(requestCode, resultCode, data);
    } else {
        Log.d(TAG, "onActivityResult handled by IABUtil.");
    }
}

// Callback for when a purchase is finished
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    @Override
    public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
        Log.d(TAG, "Purchase finished: " + result + ", purchase: "
                + purchase);
        if (result.isFailure()) {
            complain("Error purchasing: " + result);
            return;
        }
        if (!verifyDeveloperPayload(purchase)) {
            complain("Error purchasing. Authenticity verification failed.");
            return;
        }

        Log.d(TAG, "Purchase successful.");

        if (purchase.getSku().equals(SKU_INAPPITEM)) {
            // bought 1/4 tank of gas. So consume it.
            Log.d(TAG,
                    "removeAdsPurchase was succesful.. starting consumption.");
            mHelper.consumeAsync(purchase, mConsumeFinishedListener);
        }
    }
};

// Called when consumption is complete
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
    @Override
    public void onConsumeFinished(Purchase purchase, IabResult result) {
        Log.d(TAG, "Consumption finished. Purchase: " + purchase
                + ", result: " + result);

        // We know this is the "gas" sku because it's the only one we
        // consume,
        // so we don't check which sku was consumed. If you have more than
        // one
        // sku, you probably should check...
        if (result.isSuccess()) {
            // successfully consumed, so we apply the effects of the item in
            // our
            // game world's logic, which in our case means filling the gas
            // tank a bit
            Log.d(TAG, "Consumption successful. Provisioning.");
            alert("You have purchased for removing ads from your app.");
        } else {
            complain("Error while consuming: " + result);
        }
        Log.d(TAG, "End consumption flow.");
    }
};

/** Verifies the developer payload of a purchase. */
boolean verifyDeveloperPayload(Purchase p) {
    String payload = p.getDeveloperPayload();

    /*
     * TODO: verify that the developer payload of the purchase is correct.
     * It will be the same one that you sent when initiating the purchase.
     * 
     * WARNING: Locally generating a random string when starting a purchase
     * and verifying it here might seem like a good approach, but this will
     * fail in the case where the user purchases an item on one device and
     * then uses your app on a different device, because on the other device
     * you will not have access to the random string you originally
     * generated.
     * 
     * So a good developer payload has these characteristics:
     * 
     * 1. If two different users purchase an item, the payload is different
     * between them, so that one user's purchase can't be replayed to
     * another user.
     * 
     * 2. The payload must be such that you can verify it even when the app
     * wasn't the one who initiated the purchase flow (so that items
     * purchased by the user on one device work on other devices owned by
     * the user).
     * 
     * Using your own server to store and verify developer payloads across
     * app installations is recommended.
     */

    return true;
}

void complain(String message) {
    Log.e(TAG, "**** IN APP Purchase Error: " + message);
    alert(message);
}

void alert(String message) {
    Log.d(TAG, "Showing alert dialog: " + message);
    TextView resultTv = (TextView) findViewById(R.id.textView_result);
    resultTv.setText("Result : " + message);
}

}

也可以有人告诉我如何创建开发人员有效负载,我们将非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我能在这里回答主要问题^^ 如果尚未完成,则已将包含广告的活动设置为启动活动。在该Activity中的onCreate()方法中,您将在onCreate()的末尾添加以下内容:

if([Purchased?]
{
Intent adfreeactivity = new Intent(NameOfCurrentActivity.this, NameOfTargetActivity.class);
startActivity(adfreeactivity);
}

之后,您的应用应该在开始时启动正确的活动。 此外,如果用户一旦离线,最好将结果保存在SharedPreferences中,并且仅在用户在线时再次检查,并且仅在上次检查返回成功购买时才切换活动。

希望我能帮到你, MaxMüller

相关问题