簡體   English   中英

Android應用內結算:制作應用內廣告不會刪除

[英]Android In-App Billing: Ads are not removing when In-App is made

我已經在我的活動中實施了應用內結算

這是我的onIabPurchaseFinished()方法:

@Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {

    if (!verifyDeveloperPayload(info)) {
        Toast.makeText(this, R.string.error_purchasing, Toast.LENGTH_LONG).show();
    }

    Toast.makeText(this, R.string.premium_bought, Toast.LENGTH_LONG).show();

    if (info.getSku().equals("chords_premium")) {

        /** salva isPremium tra SharedPreferences */
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("status", "purchased");
        editor.apply();
    }
}

如您所見,我將字符串"status"保存到SharedPreferences以便可以從任何地方訪問它,甚至在應用程序關閉后也可以將其保存。

然后,在其他實施廣告的活動中,我這樣寫:

final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final String status = prefs.getString("status", "free");


    /** gestisce le pubblicita */
    if (status.equals("free")) {
        MobileAds.initialize(getApplicationContext(), "ca-app-pub-6723047396589178/2654753246");

        AdView listBanner = (AdView) findViewById(R.id.chords_list_banner);
        AdRequest adRequest = new AdRequest.Builder().build();
        listBanner.loadAd(adRequest);

        /** carica Ad a tutto schermo */
        chordsListAd = new InterstitialAd(this);
        chordsListAd.setAdUnitId("ca-app-pub-6723047396589178/7447672046");
        requestNewInterstitial();


        chordsListAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();
            }
        });
    }

如您在此處看到的,廣告被if statement包圍,該if statement檢查"status"字符串是否設置為free。

問題是,當我購買高級版時,仍會顯示廣告。 我該如何解決?

檢查是否購買了inapp:

//*************************************checking in app purchase has been made********************************// 
    void testInApp()
    {
        if (!blnBind) return;
        if (mService == null) return;

        int result;
        try {
            result = mService.isBillingSupported(3, getPackageName(), "inapp");

            //Toast.makeText(context, "isBillingSupported() - success : return " + String.valueOf(result), Toast.LENGTH_SHORT).show();
            Log.i(tag, "isBillingSupported() - success : return " + String.valueOf(result));
        } catch (RemoteException e) {
            e.printStackTrace();

            //Toast.makeText(context, "isBillingSupported() - fail!", Toast.LENGTH_SHORT).show();
            Log.w(tag, "isBillingSupported() - fail!");
            return;
        } 
    }

    void checkInApp()
    {

        if (!blnBind) return;
        if (mService == null) return;

        Bundle ownedItems;
        try {
            ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);

            //Toast.makeText(context, "getPurchases() - success return Bundle", Toast.LENGTH_SHORT).show();
            Log.i(tag, "getPurchases() - success return Bundle");
        } catch (RemoteException e) {
            e.printStackTrace();

            //Toast.makeText(context, "getPurchases - fail!", Toast.LENGTH_SHORT).show();
            Log.w(tag, "getPurchases() - fail!");
            return;
        }

        int response = ownedItems.getInt("RESPONSE_CODE");
        //Toast.makeText(context, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response), Toast.LENGTH_SHORT).show();
        Log.i(tag, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response));

        if (response != 0) return;

        ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
        ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
        ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE");
        String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");

        Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_ITEM_LIST\" return " + ownedSkus.toString());
        Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_DATA_LIST\" return " + purchaseDataList.toString());
        Log.i(tag, "getPurchases() - \"INAPP_DATA_SIGNATURE\" return " + (signatureList != null ? signatureList.toString() : "null"));
        Log.i(tag, "getPurchases() - \"INAPP_CONTINUATION_TOKEN\" return " + (continuationToken != null ? continuationToken : "null"));

        // TODO: management owned purchase  


        try {


            if(purchaseDataList.size()>0){
                jinapp=new JSONArray(purchaseDataList.toString());
                JSONObject c =  jinapp.getJSONObject(0);

                String productid=c.getString("productId");

                if(productid!=null){
                    SharedPreferences.Editor editor = prefpurchase.edit();
                    editor.putBoolean(Constants.APP_IS_PURCHASED,true);
                    editor.commit();
                }
            }   
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // TODO: management owned purchase  

    }

在您的SplashScreen中編寫代碼

現在,在您要展示廣告的活動/片段中,編寫以下代碼:

//*******************to check purchase has been made.If yes disable ads and no then show ads******************//
        prefpurchase = this.getSharedPreferences(Constants.GET_IN_APP_STATE, Context.MODE_PRIVATE);

        //Toast.makeText(context, "bindService - return " + String.valueOf(blnBind), Toast.LENGTH_SHORT).show();

        //In App Purchase

        ispurchased=prefpurchase.getBoolean(Constants.APP_IS_PURCHASED,false);
        System.out.println("ispurchased-->"+ispurchased);
        if(ispurchased)
        {
            setContentView(R.layout.activity_home_noads);

        }else{
            System.out.println("Getting ad");
            setContentView(R.layout.activity_home);
            //Locate the Banner Ad in activity_main.xml
            AdView adView = (AdView) this.findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder()
            // Add a test device to show Test Ads
            //.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            //.addTestDevice("B2D63***************************")
            .build();


            // Load ads into Banner Ads
            adView.loadAd(adRequest);
        }
    //*******************************************************************************************************//

邏輯很簡單, 您要創建布局的兩個版本 ,一個帶有廣告,另一個不帶有廣告。

根據sharedpreference的值加載正確的布局。

移動服務:

在onCreate()之前在啟動畫面中全局編寫以下代碼:

private IInAppBillingService mService;
    private ServiceConnection mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IInAppBillingService.Stub.asInterface(service);
        }
    };

綁定

在全球范圍內宣布blnBind:

boolean blnBind;

在SplashActivity的onCreate()中編寫:

// Bind Service
        blnBind = bindService(new Intent(
                "com.android.vending.billing.InAppBillingService.BIND"),
                mServiceConn, Context.BIND_AUTO_CREATE);

        //Toast.makeText(context, "bindService - return " + String.valueOf(blnBind), Toast.LENGTH_SHORT).show();
        Log.i(tag, "bindService - return " + String.valueOf(blnBind)); 
        //In App Purchase

GET_IN_APP_STATE或APP_IS_PURCHASED是為共享的“首選項”創建的,用作“首選項”值的鍵。

//Preferences to check in app purchase
    final static public String GET_IN_APP_STATE = "prefinapp";
    public static final String APP_IS_PURCHASED ="AppIsPurchased";

每當進行購買時,別忘了將共享首選項值設置為true。

這是因為您要將數據保存在基本上下文中,並嘗試使用(this)在當前活動上下文中找到它們。

final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

另外,一種更推薦的查詢應用內購買商品的方式是查詢應用內廣告資源,而不是存儲在sharedprefs中。

正如Google文檔中所述

查詢采購商品

成功購買后,用戶的購買數據將通過Google Play的應用內結算服務在本地緩存。 優良作法是經常查詢用戶購買的應用內結算服務,例如,每當應用啟動或恢復時,以使用戶當前的應用內商品所有權信息始終反映在您的應用中。

要從您的應用中檢索用戶的購買,請在IabHelper實例上調用queryInventoryAsync(QueryInventoryFinishedListener)。 QueryInventoryFinishedListener參數指定一個偵聽器,當查詢操作完成並處理查詢響應時,將通知該偵聽器。 從您的主線程進行此調用是安全的。

mHelper.queryInventoryAsync(mGotInventoryListener); //mHelper is IabHelper instance

如果查詢成功,則查詢結果將存儲在一個清單對象中,該對象將傳遞回偵聽器。 應用內結算服務僅返回通過當前登錄到設備的用戶帳戶進行的購買。

IabHelper.QueryInventoryFinishedListener mGotInventoryListener
   = new IabHelper.QueryInventoryFinishedListener() {
   public void onQueryInventoryFinished(IabResult result,
      Inventory inventory) {

      if (result.isFailure()) {
        // handle error here
      }
      else {
        // does the user have the premium upgrade?
        mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
        // update UI accordingly
      }
   }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM