简体   繁体   English

Android IAB - 成功购买后销毁活动

[英]Android IAB - Activity destroyed after successful purchase

I am pulling my hair out! 我把头发拉出来! At one point in the last week, I had this working. 在上周的某个时刻,我有这个工作。

I have an Android app that I am trying to add in-ap billing to. 我有一个Android应用程序,我试图添加in-ap计费。 I followed the sample TrivialDrive, and my code worked a few times. 我跟着示例TrivialDrive,我的代码工作了几次。 Now it doesn't. 现在它没有。

I am creating a simple trivia game that has a number of free questions, and the option to upgrade to get more questions. 我正在创建一个简单的琐事游戏,其中包含许多免费问题,以及升级选项以获得更多问题。 When the user completes the list of free questions, they are taken to a "Game Over" screen where they can erase their answers and start again, or upgrade. 当用户完成免费问题列表时,他们将被带到“游戏结束”屏幕,在那里他们可以删除他们的答案并重新开始或升级。

When I click the "Upgrade" button, I can make a successful purchase, but as soon as the Google "Payment Successful" dialog goes away, my activity is destroyed and I am sent back to my main activity. 当我点击“升级”按钮时,我可以成功购买,但只要Google“付款成功”对话框消失,我的活动就会被销毁,我会被发回我的主要活动。

When I try to go back and do my purchase again, my code catches the error ("You already own this item") and handles it appropriately. 当我尝试返回并再次购买时,我的代码会捕获错误(“您已拥有此项目”)并正确处理。 My code explains to the user that they already own the upgrade, and allows them to click a button to continue playing. 我的代码向用户解释他们已经拥有升级,并允许他们单击按钮继续播放。 So it looks like the OnIabPurchaseFinishedListener is firing at this point. 所以看起来OnIabPurchaseFinishedListener此时正在触发。

I have updated the Google helper code with the latest files. 我已使用最新文件更新了Google帮助程序代码。

Any help or suggestions as to where to look for answers is much appreciated. 任何有关在何处寻找答案的帮助或建议都非常感谢。

Thanks. 谢谢。

This is the relevant code for my activity: 这是我活动的相关代码:

public class GameOverActivity extends BaseActivity
{

    private IabHelper       mHelper;
    private String          m_base64EncodedPublicKey;
    private static String   THE_UPGRADE_SKU = "upgrade52";
    public static int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_over);

        setTitle("Game Over");

        Button butPlay = (Button) findViewById(R.id.buttonPlay);
        butPlay.setVisibility(View.INVISIBLE);

        PrepareIAB();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        CURRENT_ACTIVITY = ACTIVITY_GAME_OVER;
        SetMainText();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        try
        {
            if (mHelper != null)
            {
                mHelper.dispose();
                mHelper = null;
            }
        }
        catch (Exception e)
        {
        }       
    }

    private void PrepareIAB()
    {
        m_base64EncodedPublicKey = "MyKey";

        // compute your public key and store it in base64EncodedPublicKey
        mHelper = new IabHelper(this, m_base64EncodedPublicKey);
        mHelper.enableDebugLogging( true, TAG);

        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener()
        {
            public void onIabSetupFinished(IabResult result)
            {
                if (!result.isSuccess())
                {

                    ShowMessage("There was an error connecting to the Google Play Store.");
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {           
         try 
         {
            // 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.");
                }    
         }
         catch (Exception e)
         {
             super.onActivityResult(requestCode, resultCode, data); 
         }
    }



    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener   = 
            new IabHelper.OnIabPurchaseFinishedListener()
            {
                public void onIabPurchaseFinished(IabResult result, Purchase purchase)
                {
                    try 
                    {
                        if (result.isFailure())
                        {                       
                            if (result.mResponse==7)
                            {
                                UpgradeComplete();
                                ShowMessage("Thank you for upgrading.\r\n\r\nThis version has 400 more questions.");        
                            }
                            else
                            {

                                ShowMessage("Error purchasing: " + String.valueOf(result.mResponse));                           
                                UpgradeError();

                                return;
                            }

                        }
                        else if (purchase.getSku().equals(THE_UPGRADE_SKU))
                        {               
                            UpgradeComplete();
                            ShowMessage("Thank you for upgrading.\r\n\r\nThis version has 400 more questions.");                                        
                        }
                        else
                        {
                            ShowMessage("Something else happened. ");
                        }
                    }
                    catch (Exception e)
                    {
                        Log.e(TAG, e.getLocalizedMessage());
                    }

                }
            };

    private void HideUpgrade()
    {
        try 
        {
            Button btnUpgrade = (Button) findViewById(R.id.buttonUpgrade);
            if (btnUpgrade != null)
            {
                btnUpgrade.setVisibility(View.INVISIBLE);
            }           

            TextView txtMessage = (TextView) findViewById(R.id.txtUpgradeFromGameOver);
            if (txtMessage!=null)
            {
                txtMessage.setVisibility(View.INVISIBLE);   
            }   
        }
        catch (Exception e)
        {

        }        
    }

    public void onQuitButtonClick(View view)
    {
        finish();
    }

    public void onResetDBButtonClick(View view)
    {
        ConfirmResetDatabase();
    }

    private void ConfirmResetDatabase()
    {
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                switch (which)
                {
                    case DialogInterface.BUTTON_POSITIVE:

                        ResetDatabase();

                        Intent gameActivity = new Intent(getApplicationContext(), GameActivity.class);

                        gameActivity.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        // startActivityForResult(gameActivity, ACTIVITY_GAME);
                        startActivity(gameActivity);
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:
                        // No button clicked
                        break;
                }
            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Do you want to erase your score and start over?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
    }


    public void onUpgradeButtonClick(View view)
    {           
        try 
        {
            if (mHelper != null)
            {
                mHelper.launchPurchaseFlow(this, THE_UPGRADE_SKU, 10001, mPurchaseFinishedListener, m_TriviaAppInstance.AppInstallID());
            }
            else
            {
                ShowMessage("Unable to connect to Google Play Store.");         
            }   
        }
        catch (Exception e)
        {
            ShowMessage("Unable to connect to Google Play Store.");
            SendErrorMessage(e.getLocalizedMessage());          
        }
    }



    private void UpgradeComplete()
    {
        try
        {    
            HideUpgrade();

            Button butPlay = (Button) findViewById(R.id.buttonPlay);
            if (butPlay!=null)
            {
                butPlay.setVisibility(View.VISIBLE);    
            }

            TextView txtReset = (TextView) findViewById(R.id.txtGameOverRestDB);
            if (txtReset!=null)
            {
                txtReset.setVisibility(View.INVISIBLE); 
            }

            Button btnReset = (Button)findViewById(R.id.buttonResetDB);
            if (btnReset!=null)
            {
                btnReset.setVisibility(View.INVISIBLE);
            }

            m_TriviaAppInstance.SetUpgradedStatus(true);

        }
        catch (Exception e)
        {

        }

        //

    }

    private void UpgradeError()
    {
        try
        {
            Button butUpgrade;
            butUpgrade = (Button) findViewById(R.id.buttonUpgrade);
            butUpgrade.setVisibility(View.INVISIBLE);

            TextView txtMessage = (TextView) findViewById(R.id.txtUpgradeScreen);
            txtMessage.setText(R.string.upgradeScreenTextError);
        }
        catch (Exception e)
        {
        }
    }


    public void onPlayButtonClick(View view)
    {
        Intent myIntent = new Intent(view.getContext(), GameActivity.class);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivityForResult(myIntent, ACTIVITY_GAME);
    }

    public void SetMainText()
    {
        TextView txt = (TextView) findViewById(R.id.txtScoreGlobal);
        txt.setText(Integer.toString(m_TriviaAppInstance.getGlobal()) + "%");
        SetPlayerScore(1);

        if (m_TriviaAppInstance.getUpgradedStatus() == true)
        {           
            HideUpgrade();          
        }       
    }

}

FYI: I think I have this figured out - for anyone else that may come across it. 仅供参考:我想我已经想到了这一点 - 对于任何可能遇到它的人。

The activity that I was using to launch "In App Billing" was called with a "FLAG_ACTIVITY_NO_HISTORY". 我用于启动“In App Billing”的活动是使用“FLAG_ACTIVITY_NO_HISTORY”调用的。 I did this because I didn't want the user to be able to click to go back to this "Game Over" activity. 我这样做是因为我不希望用户能够点击返回到“Game Over”活动。

BUT, this causes grief with "In App Billing". 但是,这会导致“In App Billing”的悲痛。 So, make sure you don't try to launch "In App Billing" from an activity that has had the "FLAG_ACTIVITY_NO_HISTORY" set. 因此,请确保您不要尝试从已设置“FLAG_ACTIVITY_NO_HISTORY”的活动启动“In App Billing”。

My original code: 我原来的代码:

private void GameOver()
    {
        m_TriviaAppInstance.setGameOver(true);
        Intent gameOver = new Intent(getApplicationContext(), GameOverActivity.class);
        gameOver.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(gameOver);
    }

Updated code: 更新的代码:

private void GameOver()
    {
        m_TriviaAppInstance.setGameOver(true);
        Intent gameOver = new Intent(getApplicationContext(), GameOverActivity.class);       
        startActivity(gameOver);
    }

Peace 和平

I'm not high enough to comment, but bless you. 我不高,不能评论,但祝福你。 I had 我有

android:noHistory="true"

set in AndroidManifest.xml for my activity and was experiencing the same problem. 在AndroidManifest.xml中为我的活动设置并遇到了同样的问题。

Took it out and IAB is working. 拿出来,IAB正在工作。 Yay! 好极了!

Do not forget that your IabHelper.OnIabPurchaseFinishedListener is called on a different thread and before onResume() is called on your Activity! 不要忘记您的IabHelper.OnIabPurchaseFinishedListener是在另一个线程上调用的,并且在您的Activity上调用onResume()之前!

So your UpgradeComplete() or UpgradeError() can cause a crash on older devices (Crashed every time on my Gingerbread Sony Xperia Mini Pro and worked without any trouble on Samsung Galaxy S4 (Android 4.2.2) 因此,您的UpgradeComplete()或UpgradeError()可能会导致旧设备崩溃(每次在我的Gingerbread Sony Xperia Mini Pro上崩溃,并且在三星Galaxy S4(Android 4.2.2)上没有任何问题。

Caused a 3 day delay on my game.. 造成我的比赛延迟3天..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM