从另一项活动

时间:2015-06-02 13:05:56

标签: android in-app-purchase

我试图在我的第二个活动(JsInterface)的第一个活动中执行InApp Purchase调用方法。

在我的第一个活动(MainActivity)上,我有以下代码(部分):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);         
    CancelNotification(getApplicationContext(),1);
    String base64EncodedPublicKey = MY_KEY;
    mHelper = new IabHelper(this, base64EncodedPublicKey);        
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
         public void onIabSetupFinished(IabResult result) {
               if (!result.isSuccess()) { Log.d("IAB", "In-app Billing setup failed: " + result); } 
               else { 
                   Log.d("IAB", "In-app Billing is set up OK");           
                   purchaseItem("android.test.purchased");
               }
         }
    });     
    chargement();                
}

public void purchaseItem(String sku_item) {
    final String sku = sku_item;
    Log.e("PURCHASE","Accessing method");
    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase){
            Log.e("PURCHASE","Accessing method result");
            if (result.isFailure()) {
                Log.e("PURCHASE","Error : "+ sku);
                return;
            }      
            else if (purchase.getSku().equals(sku)) {
                Log.e("PURCHASE","OK : " + sku);
            }               
        }
    };
    mHelper.launchPurchaseFlow(this, sku, 10001, mPurchaseFinishedListener, MY_TOKEN);
}   

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
      if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {     
        super.onActivityResult(requestCode, resultCode, data);
      }
}

这方面一切正常:IabSetup没问题,第一个purchaseItem()被正确调用并执行。

现在我有第二个活动,它是一个在MainActivity中调用purchaseItem()方法的JsInterface:

public class jsinterface {
Context mContext;
jsinterface(Context c) { mContext = c; }        
@JavascriptInterface
public void purchaseSku(String sku) {        
    Log.e("JSInterface","Purchase SKU : " + sku);        
    MainActivity cls2= new MainActivity();
    cls2.purchaseItem(sku);
}

}

结果是我的MainActivity的purchaseItem()方法被正确调用,但是launchPurchaseFlow()或IabPurchaseFinishedListener不是。

知道为什么从MainActivity调用PurchaseFlow而不是从第二个活动调用它?

1 个答案:

答案 0 :(得分:0)

使用此库轻松进行inapp集成:

https://github.com/serso/android-checkout/blob/master/README.md

按照自述文件的说明进行操作。创建一个扩展Application的类并在那里初始化库。

现在,您可以通过调用某些功能轻松地从应用中的每个活动启动购买。