Android Open Source - game_guess_lib Guess Question Screen






From Project

Back to project page game_guess_lib.

License

The source code is released under:

MIT License

If you think the Android project game_guess_lib listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.wkmf.guess.lib.screen;
/*  w  w  w  .j  av a 2s  .c om*/
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.vending.billing.util.IabHelper;
import com.android.vending.billing.util.IabResult;
import com.android.vending.billing.util.Inventory;
import com.android.vending.billing.util.Purchase;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import com.wkmf.guess.lib.R;
import com.wkmf.guess.lib.common.Constants;
import com.wkmf.guess.lib.common.ads.GuessGameAds;
import com.wkmf.guess.lib.common.ads.GuessGameAdsListener;
import com.wkmf.guess.lib.common.dialog.DialogElement;
import com.wkmf.guess.lib.common.dialog.DialogModal;
import com.wkmf.guess.lib.data.GuessGameBDDHandler;
import com.wkmf.guess.lib.impl.GuessGameBaseApp;
import com.wkmf.guess.lib.impl.GuessGameImageDownload;
import com.wkmf.guess.lib.purchase.items.GuessGameItems;
import com.wkmf.guess.lib.structure.GuessConfig;
import com.wkmf.guess.lib.structure.GuessGame;
import com.wkmf.guess.lib.structure.GuessLevel;
import com.wkmf.guess.lib.structure.GuessQuestion;
import com.wkmf.lib.common.utils.E_CommonFunctions;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Created by ernestofndz on 19/02/14.
 */
public class GuessQuestionScreen extends GuessGameBaseApp implements GuessGameImageDownload, GuessGameAdsListener {

    private static final int ADS_PERCENT = 15;
    private static final int TAG_PADDING = 8;
    private static final int TAG_MARGIN = 2;
    private GuessLevel level;
    private GuessQuestion question;
    private int questionPos, levelPos;
    private Bitmap image;
    private DialogModal dialog;
    private AdapterView.OnItemClickListener dialogOnClick;
    private static final int DIALOG_GET_TAG = 0;
    private static final int DIALOG_REVEAL_PART_OF_ANSWER = 1;
    private static final int DIALOG_REVEAL_ANSWER = 2;
    private IabHelper mHelper; // inapp helper
    private GuessGameAds guessGameAds;
    private ProgressDialog pd;

    // callback cuando se descarga la imagen
    @Override
    public void imageDownloaded(Bitmap image) {
        this.image = image;
        // la guardamos en el dispositivo
        saveImage();
        // guardamos en bdd
        new GuessGameBDDHandler(this, GuessConfig.BDD).update(guessGame);
        // cargamos la pantalla
        if (!this.question.isCompleted()) {
            loadScreen();
        } else loadScreenCompleted();
    }

    // callback al cerrar el ad
    @Override
    public void onAdClosed() {
        this.guessGameAds.initAd(getContext(), this);
        // obtenemos la info de la siguiente pregunta
        getData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // recuperamos los datos que nos llegan de la actividad anterior
        Bundle b = getIntent().getExtras();
        if (b != null) {
            this.levelPos = b.getInt(Constants.EXTRA_GUESS_LEVEL);
            this.questionPos = b.getInt(Constants.EXTRA_GUESS_QUESTION);
            // obtenemos el nivel y la pregunta
            // comprobamos que no se haya perdido el obj de guessGame
            if (guessGame == null) guessGame = new GuessGameBDDHandler(getContext(), GuessConfig.BDD).getGuessGame();
            this.level = guessGame.getLevels().get(this.levelPos);
            this.question = this.level.getQuestions().get(this.questionPos);
            // inicializamos el contexto
            setContext(this);
            // seteamos el theme de la actividad, aunque realmente es a pantalla completa
            setTheme(config.getTheme());
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            // inicializamos el progressDialog
            this.pd = new ProgressDialog(getContext());
            // inicializamos los ads
            this.guessGameAds = new GuessGameAds();
            //this.guessGameAds.initAd(getContext(), this);
            // seteamos el layout
            setContentView(R.layout.screen_question);
            // recuperamos los datos
            getData();
            // cargamos los componentes
            loadComponents();
            // inicializamos el servicio de pagos
            initInAppHelper();
        } else {
            // mostramos mensaje y cerramos la aplicacin
            E_CommonFunctions.showMessage(getContext(), getString(R.string.error));
            finish();
        }
    }

    @Override
    protected void getData() {
        // recuperamos la imagen de la pregunta
        if (this.question.getImagePath() != null && !this.question.getImagePath().isEmpty()) {
            // ya tenemos la imagen en el sistema, o as parece
            try {
                FileInputStream in = getContext().openFileInput(this.question.getImagePath());
                this.image = BitmapFactory.decodeStream(in);
                // cargamos la pantalla
                if (!this.question.isCompleted()) {
                    loadScreen();
                } else loadScreenCompleted();
            } catch (FileNotFoundException fnfe) {
                // no se encontr el fichero, lo descargamos
                this.question.downloadImage(this, this.pd);
            }
        } else {
            // tenemos que descargar la imagen y guardarla
            this.question.downloadImage(this, this.pd);
        }
    }

    // diferenciamos de cuando una pregunta ya fue completada
    private void loadScreenCompleted() {
        // seteamos el layout
        setContentView(R.layout.screen_question);
        // seteamos la imagen
        ((ImageView) findViewById(R.id.question_image)).setImageBitmap(this.image);
        // cargamos la cabecera
        loadHeader();
        // recuperamos el cuadro de texto de la respuesta
        final TextView answerBox = (TextView) findViewById(R.id.question_answer);
        // asignamos la respuesta y bloqueamos el texto
        answerBox.setText(this.question.getAnswer());
        answerBox.setEnabled(false);
        // quitamos el botn de skip
        findViewById(R.id.question_header_skip).setVisibility(View.INVISIBLE);
        // ocultamos el botn de comprobar respuesta
        findViewById(R.id.question_check_answer).setVisibility(View.INVISIBLE);
        // ocultamos el botn de obtener ayuda
        findViewById(R.id.question_get_help).setVisibility(View.INVISIBLE);
        // ocultamos el botn de buscar ayuda
        findViewById(R.id.question_search_help).setVisibility(View.INVISIBLE);
    }

    private void loadComponents() {
        // recuperamos el cuadro de texto de la respuesta
        final TextView answerBox = (TextView) findViewById(R.id.question_answer);
        answerBox.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    E_CommonFunctions.hideKeyboard(getContext(), answerBox);
                    // hacemos la comprobacin
                    checkAnswer(answerBox.getText().toString());
                }
                return false;
            }
        });
        // ocultamos el teclado
        E_CommonFunctions.hideKeyboard(getContext(), answerBox);
        // damos funcionalidad al botn de comprobar la respuesta
        findViewById(R.id.question_check_answer).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (answerBox.getText().length() > 0) {
                    E_CommonFunctions.hideKeyboard(getContext(), answerBox);
                    // hacemos la comprobacin
                    checkAnswer(answerBox.getText().toString());
                }
            }
        });
        // damos funcionalidad al cerrar popup
        findViewById(R.id.popup_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // ocultamos el popup
                findViewById(R.id.popup_root).setVisibility(View.INVISIBLE);
                // limpiamos la respuesta anterior
                ((TextView) findViewById(R.id.question_answer)).setText("");
                // intentamos buscar otra pregunta
                skip(false);
            }
        });
        // cargamos el dialog al pulsar en ayuda
        initDialog();
        // damos funcionalidad al necesitar ayuda
        findViewById(R.id.question_get_help).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.show(dialogOnClick);
            }
        });
        // damos funcionalidad al botn de buscar ayuda mediante los tags
        findViewById(R.id.question_search_help).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // recuperamos el numero de tags
                int numTags = getTagsAmount();
                if (numTags > 0) {
                    String searchTags = "";
                    for (int i = 0; i < numTags; i++) {
                        if (searchTags.length() > 0) searchTags = searchTags.concat("+");
                        searchTags = searchTags.concat(question.getTags().get(i));
                    }
                    Uri uri = Uri.parse("http://www.google.com/#q=" + searchTags);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                } else {
                    E_CommonFunctions.showMessage(getContext(), getString(R.string.question_no_tags_for_help));
                }
            }
        });
    }

    // cargamos y pintamos los elementos de la pantalla
    @Override
    protected void loadScreen() {
        // seteamos la imagen
        ((ImageView) findViewById(R.id.question_image)).setImageBitmap(this.image);
        // cargamos los tags
        loadTags();
        // cargamos la cabecera
        loadHeader();
        // cargamos el hint
        loadHint();
        // analytics
        Tracker easyTracker = EasyTracker.getInstance(this);
        easyTracker.set(Fields.SCREEN_NAME, "Level: " + String.valueOf(this.levelPos + 1) + "-" + String.valueOf(this.questionPos + 1) + " (" + this.question.getAnswer() + ")");
        easyTracker.send(MapBuilder
                .createAppView()
                .build()
        );
        // ocultamos el progress dialog de ser necesario
        if (this.pd != null && this.pd.isShowing()) this.pd.dismiss();
    }

    // comprobamos si dispone de parte de la respuesta
    private void loadHint() {
        if (question.hasPartOfAnswer()) {
            ((TextView) findViewById(R.id.question_answer)).setHint(question.getPartOfAnswer());
        } else {
            ((TextView) findViewById(R.id.question_answer)).setHint(config.getGuessLevelType().getLevelTypeStr(this.level.getLevelType()));
        }
    }

    // guardamos la imagen en el dispositivo
    private void saveImage() {
        // generamos la ruta del fichero
        this.question.generateImagePath();
        try {
            // lo guardamos y cerramos el stream
            FileOutputStream out = getContext().openFileOutput(this.question.getImagePath(), Context.MODE_PRIVATE);
            this.image.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // cargamos los tags en pantalla
    private void loadTags() {
        // referencia al layout
        final LinearLayout tagsLayout = (LinearLayout) findViewById(R.id.question_tags);
        // vaciamos la lista
        tagsLayout.removeAllViews();
        // aadimos los nuevos tags
        for (int i = 0; i < this.question.getTags().size() && i < getTagsAmount(); i++) {
            // creamos la vista
            final TextView tag = new TextView(this);
            tag.setText(this.question.getTags().get(i));
            tag.setTextColor(Color.parseColor(config.getTagTextColor()));
            tag.setBackgroundColor(Color.parseColor(config.getTagBackgroundColor()));
            tag.setPadding(TAG_PADDING, TAG_PADDING, TAG_PADDING, TAG_PADDING);
            tag.setTypeface(null, Typeface.BOLD);
            LinearLayout.LayoutParams params
                    = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, TAG_MARGIN, 0, 0);
            tag.setLayoutParams(params);
            // aadimos la vista
            tagsLayout.addView(tag);
        }
    }

    // se cargan los tags dependiendo del nivel de dificultad y de los tags que haya pagado
    private int getTagsAmount() {
        int tagsAmount = 0;
        // primero comprobamos el nivel
        switch (this.level.getDifficulty()) {
            case GuessLevel.EASY:
                // son todos los tags
                tagsAmount = GuessQuestion.TAGS_MAX;
                break;
            case GuessLevel.MIDDLE:
                // menos un tag
                tagsAmount = GuessQuestion.TAGS_MAX - 1;
                break;
            case GuessLevel.HARD:
                // menos dos tags
                tagsAmount = GuessQuestion.TAGS_MAX - 2;
                break;
        }
        // ahora comprobamos, de ser necesario, si ha comprado ms tags
        if (tagsAmount < GuessQuestion.TAGS_MAX) {
            tagsAmount += this.question.getTagsAdded();
        }
        // devolvemos la cantidad de tags a cargar
        return tagsAmount;
    }

    // cargar la cabecera
    private void loadHeader() {
        findViewById(R.id.question_header_root).setBackgroundColor(Color.parseColor(config.getTagBackgroundColor()));
        ((TextView) findViewById(R.id.question_header_level_label)).setTextColor(Color.parseColor(config.getTagTextColor()));
        ((TextView) findViewById(R.id.question_header_level_sep)).setTextColor(Color.parseColor(config.getTagTextColor()));
        ((TextView) findViewById(R.id.question_copyrights)).setTextColor(Color.parseColor(config.getTagTextColor()));
        ((TextView) findViewById(R.id.question_header_level)).setTextColor(Color.parseColor(config.getTagTextColor()));
        ((TextView) findViewById(R.id.question_header_level)).setText(String.valueOf(this.levelPos + 1));
        ((TextView) findViewById(R.id.question_header_question)).setTextColor(Color.parseColor(config.getTagTextColor()));
        ((TextView) findViewById(R.id.question_header_question)).setText(String.valueOf(this.questionPos + 1));
        ((TextView) findViewById(R.id.question_header_life_x)).setTextColor(Color.parseColor(config.getTagTextColor()));
        ((TextView) findViewById(R.id.question_header_life_amount)).setTextColor(Color.parseColor(config.getTagTextColor()));
        ((TextView) findViewById(R.id.question_header_life_amount)).setText(String.valueOf(String.valueOf(guessGame.getLives())));
        // damos funcin al botn de skip
        findViewById(R.id.question_header_skip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // intentamos saltar la pregunta
                skip(true);
            }
        });
    }

    // saltar pregunta
    private void skip(boolean skip) {
        boolean skipped = false;
        for (int i = this.questionPos + 1; i < this.level.getQuestions().size(); i++) {
            if (!this.level.getQuestions().get(i).isCompleted()) {
                skipped = true;
                this.question = this.level.getQuestions().get(i);
                this.questionPos = i;
                break;
            }
        }
        if (!skipped) {
            // buscamos desde el principio
            for (int i = 0; i < this.questionPos; i++) {
                if (!this.level.getQuestions().get(i).isCompleted()) {
                    skipped = true;
                    this.question = this.level.getQuestions().get(i);
                    this.questionPos = i;
                    break;
                }
            }
        }
        // si conseguimos nueva pregunta que no haya sido respondida, la cargamos
        if (skipped) {
            //if (this.guessGameAds.isAdLoaded() && E_CommonFunctions.randomizeAd(ADS_PERCENT)) {
                //cleanGC();
                //this.guessGameAds.showAd();
            //} else {
                cleanGC();
                getData();
            //}
        } else {
            // no hay ms preguntas en ste nivel que haga falta responder
            if (skip) {
                E_CommonFunctions.showMessage(this, getString(R.string.question_no_more_questions), Toast.LENGTH_LONG);
            } else {
                E_CommonFunctions.showMessage(this, getString(R.string.question_level_completed), Toast.LENGTH_LONG);
                // y salimos de nivel
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    // comprobamos la respuesta
    private void checkAnswer(String answer) {
        if (this.question.checkAnswer(answer)) {
            // el premio
            int prize = this.level.getCorrectAnswerPrize();
            // mostramos el mensaje de respuesta correcta
            findViewById(R.id.popup_root).setVisibility(View.VISIBLE);
            // e indicamos cuantas vidas ha ganado
            ((TextView) findViewById(R.id.popup_earned)).setText(String.valueOf(prize));
            // marcamos la pregunta como correcta
            this.question.setCompleted(true);
            // damos el premio por responder correctamente la respuesta
            guessGame.addLives(prize);
            // cargamos la cabecera nuevamente
            loadHeader();
            // y guardamos en bdd
            new GuessGameBDDHandler(getContext(), GuessConfig.BDD).update(guessGame);
            // asignamos RESULT OK para avisar a la tarea anterior
            setResult(RESULT_OK);
        } else {
            E_CommonFunctions.showMessage(getContext(), getString(R.string.question_answer_incorrect));
        }
    }

    @Override
    protected void resultOK() {
        // no hacemos nada de momento
    }

    // opciones del dilogo al pulsar en ayuda
    private void initDialog() {
        // inicializamos el dialog
        this.dialog = new DialogModal(getContext());
        // aadimos las opciones
        // GET A NEW TAG
        this.dialog.addElement(
                new DialogElement(
                        DIALOG_GET_TAG,
                        getString(R.string.question_dialog_get_tag),
                        getResources().getDrawable(R.drawable.action_help),
                        GuessGame.LIVES_AMOUNT_GET_TAG));
        // REVEAL PART OF ANSWER
        this.dialog.addElement(
                new DialogElement(
                        DIALOG_REVEAL_PART_OF_ANSWER,
                        getString(R.string.question_dialog_reveal_part_of_answer),
                        getResources().getDrawable(R.drawable.action_help),
                        GuessGame.LIVES_AMOUNT_REVEAL_PART_OF_ANSWER));
        // REVEAL ANSWER
        this.dialog.addElement(
                new DialogElement(
                        DIALOG_REVEAL_ANSWER,
                        getString(R.string.question_dialog_reveal_answer),
                        getResources().getDrawable(R.drawable.action_help),
                        GuessGame.LIVES_AMOUNT_REVEAL_ANSWER));
        // creamos el listener
        this.dialogOnClick = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // elemento pulsado del dialog
                DialogElement element = (DialogElement) parent.getItemAtPosition(position);
                switch (element.getId()) {
                    // GET A NEW TAG
                    case DIALOG_GET_TAG:
                        // comprobamos que se puede aadir un tag
                        if (getTagsAmount() < GuessQuestion.TAGS_MAX) {
                            // comprobamos que disponga de suficientes vidas
                            if (guessGame.getLives() >= element.getAmount()) {
                                // aadimos un tag
                                question.addTag();
                                // borramos la vida
                                guessGame.removeLives(element.getAmount());
                                // recargamos la lista de tags
                                loadTags();
                                // recargamos el header
                                loadHeader();
                                // actualizamos en BDD
                                new GuessGameBDDHandler(getContext(), GuessConfig.BDD).update(guessGame);
                            } else {
                                // al no tener vidas mostramos el dilogo para comprarlas
                                showInAppPurchaseDialog();
                            }
                        } else {
                            // no hay ms tags disponibles
                            E_CommonFunctions.showMessage(getContext(), getString(R.string.question_no_more_tags));
                        }
                        break;

                        // REVEAL PART OF THE ANSWER
                    case DIALOG_REVEAL_PART_OF_ANSWER:
                        // comprobamos que no la haya solicitado anteriormente
                        if (!question.hasPartOfAnswer()) {
                            // comprobamos que disponga de suficientes vidas
                            if (guessGame.getLives() >= element.getAmount()) {
                                // revelamos parte de la respuesta
                                question.revealPartOfAnswer();
                                // borramos la vida
                                guessGame.removeLives(element.getAmount());
                                // mostramos el nuevo hint
                                loadHint();
                                // recargamos el header
                                loadHeader();
                                // actualizamos en BDD
                                new GuessGameBDDHandler(getContext(), GuessConfig.BDD).update(guessGame);
                            } else {
                                // al no tener vidas mostramos el dilogo para comprarlas
                                showInAppPurchaseDialog();
                            }
                        } else {
                            // ya lo solicit anteriormente
                            E_CommonFunctions.showMessage(getContext(), getString(R.string.question_no_reveal_part_of_answer_available));
                        }
                        break;

                    // REVEAL ANSWER
                    case DIALOG_REVEAL_ANSWER:
                        // comprobamos que disponga de suficientes vidas
                        if (guessGame.getLives() >= element.getAmount()) {
                            // borramos la vida
                            guessGame.removeLives(element.getAmount());
                            // marcamos que se ha respondido la pregunta
                            question.setCompleted(true);
                            // recargamos la pantalla
                            loadScreenCompleted();
                            // marcamos el result para que se actualice
                            setResult(RESULT_OK);
                            // actualizamos en BDD
                            new GuessGameBDDHandler(getContext(), GuessConfig.BDD).update(guessGame);
                        } else {
                            // al no tener vidas mostramos el dilogo para comprarlas
                            showInAppPurchaseDialog();
                        }
                        break;
                }
                // cerramos el dialogo
                dialog.dismiss();
            }
        };
    }

    // mostramos el dialogo para comprar vidas
    private void showInAppPurchaseDialog() {
        // mostramos la alerta para confirmar que desea ver la oferta
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getString(R.string.purchase_lives_title));
        dialog.setMessage(getString(R.string.purchase_lives_message));
        dialog.setCancelable(false);
        dialog.setPositiveButton(getString(R.string.purchase_lives_button_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // lanzamos la compra
                mHelper.launchPurchaseFlow(
                        (Activity) getContext(),
                        GuessGameItems.SKU_90_LIVES,
                        GuessGameItems.RC_REQUEST,
                        mPurchaseFinishedListener,
                        guessGame.getPayload());

            }
        });
        dialog.setNegativeButton(getString(R.string.purchase_lives_button_cancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    // inicializamos los datos de pago
    private void initInAppHelper() {
        mHelper = new IabHelper(this, config.getBase64());
        mHelper.enableDebugLogging(true);
        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                if (!result.isSuccess()) {
                    // error
                    E_CommonFunctions.showMessage(getContext(), getString(R.string.error) + result.getMessage());
                    return;
                }
                if (mHelper == null) return;
                mHelper.queryInventoryAsync(mGotInventoryListener);
            }
        });
    }

    // se llama al terminar de recuperar los items que tenemos en el inventario
    IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            if (mHelper == null) return;
            // comprobamos que no haya fallado
            if (result.isFailure()) {
                E_CommonFunctions.showMessage(getContext(), getString(R.string.error_purchase), Toast.LENGTH_LONG);
                return;
            }
            // comprobamos el paquete
            Purchase lives = inventory.getPurchase(GuessGameItems.SKU_90_LIVES);
            if (lives != null && lives.getDeveloperPayload().equals(guessGame.getPayload())) {
                mHelper.consumeAsync(inventory.getPurchase(GuessGameItems.SKU_90_LIVES), mConsumeFinishedListener);
                return;
            }
        }
    };

    // se llama cuando la compra ha terminado
    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
            if (mHelper == null) return;
            if (result.isFailure() || !purchase.getDeveloperPayload().equals(guessGame.getPayload())) {
                // fall la compra
                E_CommonFunctions.showMessage(getContext(), getString(R.string.error_purchase), Toast.LENGTH_LONG);
                return;
            }
            // compra correcta
            if (purchase.getSku().equals(GuessGameItems.SKU_90_LIVES)) {
                // ha comprado un pack de vidas
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            }
        }
    };

    // se llama cuando se consumen los items
    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
        public void onConsumeFinished(Purchase purchase, IabResult result) {
            if (mHelper == null) return;
            // deberamos comprobar el item, pero como disponemos solo de un pack de vidas..
            if (result.isSuccess()) {
                // aadimos las vidas
                guessGame.addLives(GuessGameItems.PACK_90_LIVES);
                new GuessGameBDDHandler(getContext(), GuessConfig.BDD).update(guessGame);
                loadHeader();
            }
        }
    };

    // limpiamos para evitar out of memory error
    private void cleanGC() {
        ((ImageView) findViewById(R.id.question_image)).setImageBitmap(null);
        if (this.image != null && !this.image.isRecycled()) {
            this.image.recycle();
            this.image = null;
        }
        System.gc();
    }

    // en el onpause evitamos los window leak
    @Override
    protected void onPause() {
        super.onPause();
        if (this.pd != null && this.pd.isShowing()) {
            this.pd.dismiss();
        }
    }

    // importante eliminar el helper cuando se finaliza la actividad
    @Override
    public void onDestroy() {
        super.onDestroy();
        cleanGC();
        if (mHelper != null) {
            mHelper.dispose();
            mHelper = null;
        }
    }

    @Override
    public void onBackPressed() {
        cleanGC();
        super.onBackPressed();
    }

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

    @Override
    protected void onStart() {
        super.onStart();
        EasyTracker.getInstance(this).activityStart(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EasyTracker.getInstance(this).activityStop(this);
    }
}




Java Source Code List

com.android.vending.billing.util.Base64DecoderException.java
com.android.vending.billing.util.Base64.java
com.android.vending.billing.util.IabException.java
com.android.vending.billing.util.IabHelper.java
com.android.vending.billing.util.IabResult.java
com.android.vending.billing.util.Inventory.java
com.android.vending.billing.util.Purchase.java
com.android.vending.billing.util.Security.java
com.android.vending.billing.util.SkuDetails.java
com.wkmf.guess.lib.common.Constants.java
com.wkmf.guess.lib.common.ads.GuessGameAdsListener.java
com.wkmf.guess.lib.common.ads.GuessGameAds.java
com.wkmf.guess.lib.common.api.GuessApi.java
com.wkmf.guess.lib.common.api.GuessRestApi.java
com.wkmf.guess.lib.common.async.DownloadTask.java
com.wkmf.guess.lib.common.dialog.DialogElement.java
com.wkmf.guess.lib.common.dialog.DialogModalListAdapter.java
com.wkmf.guess.lib.common.dialog.DialogModal.java
com.wkmf.guess.lib.data.GuessGameBDDHandler.java
com.wkmf.guess.lib.data.GuessSQL.java
com.wkmf.guess.lib.impl.GuessGameBaseApp.java
com.wkmf.guess.lib.impl.GuessGameImageDownload.java
com.wkmf.guess.lib.impl.GuessGameInterface.java
com.wkmf.guess.lib.purchase.items.GuessGameItems.java
com.wkmf.guess.lib.screen.GuessLevelScreen.java
com.wkmf.guess.lib.screen.GuessMainScreen.java
com.wkmf.guess.lib.screen.GuessQuestionScreen.java
com.wkmf.guess.lib.screen.adapter.LevelsAdapter.java
com.wkmf.guess.lib.screen.adapter.QuestionsAdapter.java
com.wkmf.guess.lib.service.GuessGameService.java
com.wkmf.guess.lib.service.GuessGameUpdater.java
com.wkmf.guess.lib.service.ServiceStarter.java
com.wkmf.guess.lib.structure.GuessConfig.java
com.wkmf.guess.lib.structure.GuessDrawable.java
com.wkmf.guess.lib.structure.GuessGame.java
com.wkmf.guess.lib.structure.GuessLevelType.java
com.wkmf.guess.lib.structure.GuessLevel.java
com.wkmf.guess.lib.structure.GuessQuestion.java