fr.shywim.antoinedaniel.ui.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for fr.shywim.antoinedaniel.ui.MainActivity.java

Source

/*
 * Copyright (c) 2015 Matthieu Harl
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package fr.shywim.antoinedaniel.ui;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.SearchManager;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.graphics.PorterDuff;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.IntDef;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.vending.billing.IInAppBillingService;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.actions.SearchIntents;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.games.Games;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;

import fr.shywim.antoinedaniel.BuildConfig;
import fr.shywim.antoinedaniel.Installation;
import fr.shywim.antoinedaniel.R;
import fr.shywim.antoinedaniel.appwidget.HomeScreenWidgetProvider;
import fr.shywim.antoinedaniel.sync.AppState;
import fr.shywim.antoinedaniel.ui.fragment.FragmentsCallbacks;
import fr.shywim.antoinedaniel.ui.fragment.GamesFragment;
import fr.shywim.antoinedaniel.ui.fragment.NewsFragment;
import fr.shywim.antoinedaniel.ui.fragment.SoundPagerFragment;
import fr.shywim.antoinedaniel.ui.fragment.TaskFragment;
import fr.shywim.antoinedaniel.ui.fragment.VideoListFragment;
import fr.shywim.antoinedaniel.utils.AboutUtils;
import fr.shywim.antoinedaniel.utils.AnalyticsUtils;
import fr.shywim.antoinedaniel.utils.AppConstants;
import fr.shywim.antoinedaniel.utils.PrefUtils;
import fr.shywim.antoinedaniel.utils.Utils;
import io.fabric.sdk.android.Fabric;

public class MainActivity extends ActionBarActivity
        implements GamesFragment.ActivityCallbacksGames, FragmentsCallbacks, TaskFragment.TaskCallbacks {
    // Request codes
    public static final int SETTINGS_REQUEST_CODE = 231;
    public static final int PURCHASE_REQUEST_CODE = 100;
    public static final int RESULT_CONNECT_GOOGLE_CODE = 300;
    // IAP Service
    private static IInAppBillingService IAPService;
    private static boolean IAPBound = false;
    // Navigation Drawer
    private DrawerLayout mDrawerLayout;
    private ArrayList<Integer> mNavDrawerItems = new ArrayList<>();
    private View[] mNavDrawerItemViews;
    private int mNavDrawerSelectedItem = -1;
    private final int[] NAV_DRAWER_DRAWABLE_IDS = { R.drawable.ic_drawer_news, R.drawable.ic_drawer_sounds,
            R.drawable.ic_drawer_videos, R.drawable.ic_drawer_games, R.drawable.ic_drawer_achievements,
            R.drawable.ic_drawer_leaderboards };
    private final int[] NAV_DRAWER_STRING_IDS = { R.string.drawer_news, R.string.drawer_sounds,
            R.string.drawer_videos, R.string.drawer_games, R.string.drawer_achievements,
            R.string.drawer_leaderboards, R.string.drawer_donate, R.string.drawer_settings, R.string.drawer_help,
            R.string.drawer_about, R.string.drawer_debug };
    // Retained TaskFragment
    private TaskFragment mTaskFragment;
    private static final String TAG_TASK_FRAGMENT = "tag_task_fragment";
    // Primary toolbar
    private Toolbar mActionBarToolbar;
    private String mActionBarToolbarTitle;
    // AdMob
    private AdView mAdView;

    private Handler mHandler;
    // Google Play Services
    private static final int VIEW_ID_POPUPS = R.id.main_layout;
    boolean initBegan = false;
    boolean adViewLoaded = false;
    boolean donated;
    ActionBarDrawerToggle drawerToggle;
    Utils utils;
    AppState appState;
    Context mContext;
    Context mAppContext;

    public String searchQuery;

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({ SOUNDS, VIDEOS, GAMES, ACHIEVEMENTS, LEADERBOARDS, DONATE, SETTINGS, HELP, ABOUT, NEWS, SEPARATOR,
            HEADER })
    public @interface DrawerItem {
    }

    public static final int NEWS = 0;
    public static final int SOUNDS = 1;
    public static final int VIDEOS = 2;
    public static final int GAMES = 3;
    public static final int ACHIEVEMENTS = 4;
    public static final int LEADERBOARDS = 5;
    public static final int DONATE = 6;
    public static final int SETTINGS = 7;
    public static final int HELP = 8;
    public static final int ABOUT = 9;
    public static final int DEBUG = 10;
    public static final int SEPARATOR = -1;
    public static final int HEADER = -2;

    public static final class LoaderID {
        public static final int SOUND_FILTER = 0;
        public static final int SOUND_PLAYER = 10;
        public static final int SOUND_BOSSES = 11;
        public static final int SOUND_SALUTATIONS = 12;
        public static final int VIDEO_DETAILS_SOUNDS = 20;
        public static final int VIDEO_DETAILS_MUSICS = 21;
    }

    //**********************************************************************************************
    //* Activity Override                                                                          *
    //**********************************************************************************************
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Crashlytics not initialized, only safe code
        mContext = this;

        Fabric.with(this, new Crashlytics());
        Crashlytics.setUserIdentifier(Installation.id(this));

        // Crashlytics initialized, can start doing "unsafe" code
        AnalyticsUtils.initAnalyticsTracker(getApplicationContext());
        mHandler = new Handler();
        mAppContext = this.getApplicationContext();
        utils = Utils.getInstance();
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        setContentView(R.layout.activity_main);

        Intent intent = getIntent();
        if (SearchIntents.ACTION_SEARCH.equals(intent.getAction())) {
            searchQuery = intent.getStringExtra(SearchManager.QUERY);
        }

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }

        attachTaskFragment();

        appState = AppState.getInstance();
        appState.load(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!utils.signInFlowStarted) {
            mTaskFragment.connectPlayServices(findViewById(VIEW_ID_POPUPS));
        }

        if (!IAPBound) {
            Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
            intent.setPackage("com.android.vending");
            if (mAppContext != null) {
                IAPBound = mAppContext.bindService(intent, IAPConnection, Context.BIND_AUTO_CREATE);
            }
        }
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        setupNavDrawer();
        setupAdMob();
        if (savedInstanceState == null) {
            goToNavDrawerItem(SOUNDS);
        } else {
            formatNavDrawer();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (adViewLoaded)
            mAdView.resume();
        fadeIn();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case SETTINGS_REQUEST_CODE:
            AppWidgetManager man = AppWidgetManager.getInstance(this);
            if (man != null) {
                int[] ids = man.getAppWidgetIds(new ComponentName(mAppContext, HomeScreenWidgetProvider.class));
                Intent updateIntent = new Intent();
                updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                updateIntent.putExtra(HomeScreenWidgetProvider.WIDGET_IDS_KEY, ids);
                this.sendBroadcast(updateIntent);
            }

            if (resultCode == RESULT_CONNECT_GOOGLE_CODE) {
                mTaskFragment.connectPlayServices(findViewById(VIEW_ID_POPUPS));
            }
            break;

        case PURCHASE_REQUEST_CODE:
            if (resultCode == RESULT_OK) {
                String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
                try {
                    JSONObject jo = new JSONObject(purchaseData);
                    String sku = jo.getString("productId");
                    if (sku.equals(utils.SKU_DONATE)) {
                        PrefUtils.setUserDonated(this, true);
                        Toast.makeText(this, R.string.toast_purchase_thanks, Toast.LENGTH_LONG).show();
                        mAdView.destroy();
                        LinearLayout adLayout = (LinearLayout) findViewById(R.id.adLayout);
                        adLayout.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT).show();
                }
            }
            break;

        case BlindGameActivity.REQUEST_CODE:
            /*if (resultCode == RESULT_OK){
               selectItem(DrawerPosition.GAMES, data.getExtras());
            } else selectItem(DrawerPosition.GAMES, null);*/
            break;

        case 1001:
            if (resultCode == RESULT_OK) {
                mTaskFragment.connectPlayServices(findViewById(VIEW_ID_POPUPS));
            } else {
                PrefUtils.setRefusedGoogle(this, true);
            }
            break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_purchase_ad:
            startBuyFlow();
            return true;
        case R.id.action_discover_wtc:
            final String TRAILER = this.getResources().getString(R.string.youtube_video_trailer);
            final String ANNIV = this.getResources().getString(R.string.youtube_video_anniv);
            CharSequence[] items = new CharSequence[] { getString(R.string.video_trailer_name),
                    getString(R.string.video_2ans_name) };
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.choose_video));
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                    case 0:
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(TRAILER)));
                        break;
                    case 1:
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(ANNIV)));
                        break;
                    }
                }
            });
            builder.show();
            return true;
        case R.id.action_facebook_app:
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.facebook_bad))));
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onPause() {
        super.onPause();
        appState.save(this);
        if (initBegan) {
            if (adViewLoaded)
                mAdView.pause();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (initBegan && adViewLoaded)
            mAdView.destroy();
        if (IAPBound && IAPService != null) {
            IAPBound = false;
        }
    }

    private void attachTaskFragment() {
        FragmentManager fm = getSupportFragmentManager();
        mTaskFragment = (TaskFragment) fm.findFragmentByTag(TAG_TASK_FRAGMENT);

        if (mTaskFragment == null) {
            mTaskFragment = new TaskFragment();
            fm.beginTransaction().add(mTaskFragment, TAG_TASK_FRAGMENT).commit();
        }
    }

    /**
     * Fade in main content view if view has been faded out.
     */
    private void fadeIn() {
        View mainLayout = findViewById(R.id.content);
        if (mainLayout != null) {
            if (mainLayout.getAlpha() != 1.0f) {
                mainLayout.clearAnimation();
                mainLayout.animate().alpha(1).setDuration(getResources().getInteger(R.integer.anim_duration_fast));
            }
        }
    }

    @Override
    public void onGoogleApiClientConnected() {
        getSharedPreferences(AppConstants.GOOGLE_PREFS, MODE_PRIVATE).edit()
                .putBoolean(AppConstants.GOOGLE_CONNECTED, true).apply();
        // Update the Navigation Drawer
        populateNavDrawer();
        formatNavDrawer();
        // Google+ sign-in related views in GamesFragment
        View view = findViewById(R.id.sign_in_button);
        if (view != null) {
            view.setVisibility(View.GONE);
        }
        view = findViewById(R.id.sign_in_controll);
        if (view != null) {
            ((ImageView) view).setColorFilter(getResources().getColor(R.color.primary), PorterDuff.Mode.MULTIPLY);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, R.string.gplay_connected, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    public void onGoogleApiClientFailed(ConnectionResult result) {
        try {
            result.startResolutionForResult(this, 1001);
        } catch (IntentSender.SendIntentException e) {
            Crashlytics.logException(e);
        }
    }

    //**********************************************************************************************
    //* Navigation Drawer                                                                          *
    //**********************************************************************************************
    private void setupNavDrawer() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (mDrawerLayout == null) {
            return;
        }

        mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.primary));
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);

        setupNavDrawerButton();

        populateNavDrawer();
    }

    private void setupNavDrawerButton() {
        if (mActionBarToolbar != null) {
            mActionBarToolbar.setNavigationIcon(R.drawable.ic_drawer);
            mActionBarToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mDrawerLayout.openDrawer(Gravity.START);
                }
            });
        }
    }

    private void populateNavDrawer() {
        mNavDrawerItems.clear();

        mNavDrawerItems.add(HEADER);

        mNavDrawerItems.add(NEWS);
        mNavDrawerItems.add(SOUNDS);
        mNavDrawerItems.add(VIDEOS);
        mNavDrawerItems.add(GAMES);

        mNavDrawerItems.add(SEPARATOR);

        if (mTaskFragment.isGoogleApiClientConnected()) {
            // TODO: Check for replacement [GoogleApiClient]
            mNavDrawerItems.add(ACHIEVEMENTS);
            mNavDrawerItems.add(LEADERBOARDS);

            mNavDrawerItems.add(SEPARATOR);
        }

        if (!donated) {
            // TODO: Check for replacement [donate]
            mNavDrawerItems.add(DONATE);
        }
        mNavDrawerItems.add(SETTINGS);
        mNavDrawerItems.add(HELP);
        mNavDrawerItems.add(ABOUT);
        if (BuildConfig.DEBUG) {
            mNavDrawerItems.add(DEBUG);
        }
        createNavDrawerItems();
    }

    private void createNavDrawerItems() {
        LinearLayout navDrawer = (LinearLayout) findViewById(R.id.nav_drawer);
        if (navDrawer == null) {
            return;
        }

        mNavDrawerItemViews = new View[mNavDrawerItems.size()];
        navDrawer.removeAllViews();
        for (int i = 0; i < mNavDrawerItems.size(); i++) {
            mNavDrawerItemViews[i] = makeNavDrawerItem(mNavDrawerItems.get(i), navDrawer);
            navDrawer.addView(mNavDrawerItemViews[i]);
        }
    }

    private View makeNavDrawerItem(final int itemId, ViewGroup container) {
        int layout;
        if (itemId == SEPARATOR) {
            layout = R.layout.navdrawer_separator;
        } else if (itemId == HEADER) {
            layout = R.layout.navdrawer_header;
        } else {
            layout = R.layout.navdrawer_item;
        }

        View view = getLayoutInflater().inflate(layout, container, false);

        if (itemId == SEPARATOR || itemId == HEADER) {
            // TODO: Header click
            // TODO: Accessibility?
            return view;
        }

        ImageView iconView = (ImageView) view.findViewById(R.id.icon);
        TextView titleView = (TextView) view.findViewById(R.id.title);
        int iconId = itemId >= 0 && itemId < NAV_DRAWER_DRAWABLE_IDS.length ? NAV_DRAWER_DRAWABLE_IDS[itemId] : 0;
        int titleId = itemId >= 0 && itemId < NAV_DRAWER_STRING_IDS.length ? NAV_DRAWER_STRING_IDS[itemId] : 0;

        iconView.setVisibility(iconId == 0 ? View.GONE : View.VISIBLE);
        if (iconId > 0) {
            iconView.setImageResource(iconId);
        }
        titleView.setText(titleId);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNavDrawerItemClick(itemId);
            }
        });

        return view;
    }

    private void onNavDrawerItemClick(@DrawerItem final int itemId) {
        // Delay to allow the drawer animation to play
        goToNavDrawerItem(itemId);

        mDrawerLayout.closeDrawer(Gravity.START);
    }

    private boolean isSpecialItem(@DrawerItem int itemId) {
        return itemId == ACHIEVEMENTS || itemId == LEADERBOARDS || itemId == DONATE || itemId == ABOUT;
    }

    private boolean isSeparator(@DrawerItem int itemId) {
        return itemId == SEPARATOR || itemId == HEADER;
    }

    private void formatNavDrawerItem(View view, int itemId, boolean selected) {
        if (isSeparator(itemId)) {
            return;
        }

        ImageView iconView = (ImageView) view.findViewById(R.id.icon);
        TextView titleView = (TextView) view.findViewById(R.id.title);

        titleView.setTextColor(selected ? getResources().getColor(R.color.navdrawer_text_color_selected)
                : getResources().getColor(R.color.navdrawer_text_color));
        iconView.setColorFilter(selected ? getResources().getColor(R.color.navdrawer_icon_tint_selected)
                : getResources().getColor(R.color.navdrawer_icon_tint));
    }

    private void setSelectedNavDrawerItem(int itemId) {
        mNavDrawerSelectedItem = itemId;
        formatNavDrawer();
    }

    private void formatNavDrawer() {
        if (mNavDrawerItemViews != null) {
            for (int i = 0; i < mNavDrawerItemViews.length; i++) {
                if (i < mNavDrawerItems.size()) {
                    int thisItemId = mNavDrawerItems.get(i);
                    formatNavDrawerItem(mNavDrawerItemViews[i], thisItemId, mNavDrawerSelectedItem == thisItemId);
                }
            }
        }
    }

    private boolean isSelected(int itemId) {
        return mNavDrawerSelectedItem == itemId;
    }

    private void goToNavDrawerItem(@DrawerItem int itemId) {
        if (isSelected(itemId)) {
            return;
        }
        Fragment newFragment = null;
        switch (itemId) {
        case NEWS:
            newFragment = NewsFragment.newInstance();
            break;
        case SOUNDS:
            newFragment = new SoundPagerFragment();
            break;
        case VIDEOS:
            newFragment = new VideoListFragment();
            break;
        case GAMES:
            newFragment = GamesFragment.newInstance();
            break;
        case ACHIEVEMENTS:
            startActivityForResult(Games.Achievements.getAchievementsIntent(mTaskFragment.getGoogleApiClient()), 0);
            break;
        case LEADERBOARDS:
            startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(mTaskFragment.getGoogleApiClient()),
                    0);
            break;
        case DONATE:
            startBuyFlow();
            break;
        case SETTINGS:
            startActivity(new Intent(this, SettingsActivity.class));
            break;
        case HELP:
            startActivity(new Intent(this, HelpActivity.class));
            break;
        case ABOUT:
            AboutUtils.showAbout(this);
            break;
        case DEBUG:
            AboutUtils.showDebug(this);
            break;
        }

        if (newFragment != null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out);
            ft.replace(R.id.content, newFragment);
            ft.commit();
        }
    }

    //**********************************************************************************************
    //* AdMob                                                                                      *
    //**********************************************************************************************
    private void setupAdMob() {
        boolean donated = PrefUtils.hasUserDonated(this);
        LinearLayout adLayout = (LinearLayout) findViewById(R.id.adLayout);
        if (!BuildConfig.DEBUG && Utils.isNetworkAvailable(this) && !donated) {
            mAdView = new AdView(this);
            mAdView.setAdUnitId(getString(R.string.admob_id));
            mAdView.setAdSize(AdSize.SMART_BANNER);
            adLayout.addView(mAdView);
            AdRequest adRequest = new AdRequest.Builder().build();
            mAdView.loadAd(adRequest);
            adViewLoaded = true;
        } else {
            removeAdMobLayout();
        }
    }

    private void removeAdMobLayout() {
        View adLayout = findViewById(R.id.adLayout);
        if (adLayout != null) {
            adLayout.setVisibility(View.GONE);
        }
        destroyAdMob();
    }

    private void destroyAdMob() {
        if (mAdView != null) {
            mAdView.destroy();
            mAdView = null;
        }
    }

    //******************************
    //* GCM + Google Play Services *
    //******************************

    void startBuyFlow() {
        if (IAPService == null) {
            // TODO: res
            Toast.makeText(this, "Impossible de faire des achats sur un appareil non support par Google.",
                    Toast.LENGTH_LONG).show();
            return;
        }

        try {
            Bundle buyIntentBundle = IAPService.getBuyIntent(3, getPackageName(), utils.SKU_DONATE, "inapp", null);
            int responseCode = (int) buyIntentBundle.get("RESPONSE_CODE");
            switch (responseCode) {
            case 0: // BILLING_RESPONSE_RESULT_OK
                PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
                try {
                    if (pendingIntent != null) {
                        IntentSender sender = pendingIntent.getIntentSender();
                        startIntentSenderForResult(sender, PURCHASE_REQUEST_CODE, new Intent(), 0, 0, 0);
                    }
                } catch (IntentSender.SendIntentException e) {
                    Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT).show();
                }
                break;
            case 1: // BILLING_RESPONSE_RESULT_USER_CANCELED
                break;
            case 3: // BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE
                Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT);
                break;
            case 4: // BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE
                Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT);
                break;
            case 5: // BILLING_RESPONSE_RESULT_DEVELOPER_ERROR
                Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT);
                break;
            case 6: // BILLING_RESPONSE_RESULT_ERROR
                Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT);
                break;
            case 7: // BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED
                PrefUtils.setUserDonated(this, true);
                Toast.makeText(mContext, R.string.toast_purchase_thanks, Toast.LENGTH_LONG).show();
                mAdView.destroy();
                LinearLayout adLayout = (LinearLayout) findViewById(R.id.adLayout);
                adLayout.setVisibility(View.GONE);
                break;
            case 8: // BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED
                break;
            }
        } catch (RemoteException e) {
            Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT).show();
        }
    }

    //************
    //* Services *
    //************
    final ServiceConnection IAPConnection = new ServiceConnection() {

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

        @Override
        public void onServiceDisconnected(ComponentName className) {
            IAPService = null;
            IAPBound = false;
        }
    };

    // GameCallbacks Interface
    @Override
    public boolean isConnected() {
        return mTaskFragment.isGoogleApiClientConnected();
    }

    @Override
    public void connect() {
        mTaskFragment.connectPlayServices(findViewById(VIEW_ID_POPUPS));
    }

    @Override
    public void showLeaderboard(int which) {
        Intent intent = Games.Leaderboards.getLeaderboardIntent(mTaskFragment.getGoogleApiClient(),
                getString(which));
        startActivityForResult(intent, 0);
    }

    @Override
    public void showAchievements() {
        Intent intent = Games.Achievements.getAchievementsIntent(mTaskFragment.getGoogleApiClient());
        startActivityForResult(intent, 0);
    }

    //**********************************************************************************************
    //* FragmentsCallbacks                                                                         *
    //**********************************************************************************************
    @Override
    public void setActionBarTitle(int resId) {
        if (mActionBarToolbar != null) {
            mActionBarToolbar.setTitle(resId);
            if (mActionBarToolbarTitle != null) {
                mActionBarToolbarTitle = null;
            }
        } else {
            mActionBarToolbarTitle = getString(resId);
        }
    }

    @Override
    public void setActionBarToolbar(Toolbar toolbar) {
        mActionBarToolbar = toolbar;
        if (mActionBarToolbar != null) {
            setSupportActionBar(mActionBarToolbar);
            if (mActionBarToolbarTitle != null) {
                mActionBarToolbar.setTitle(mActionBarToolbarTitle);
                mActionBarToolbarTitle = null;
            }
        }
        setupNavDrawerButton();
    }

    @Override
    public void onFragmentAttached(Fragment fragment) {
        int itemId;
        if (fragment instanceof SoundPagerFragment) {
            itemId = SOUNDS;
        } else if (fragment instanceof VideoListFragment) {
            itemId = VIDEOS;
        } else if (fragment instanceof GamesFragment) {
            itemId = GAMES;
        } else if (fragment instanceof NewsFragment) {
            itemId = NEWS;
        } else {
            return;
        }
        setSelectedNavDrawerItem(itemId);
    }
}