com.tapcentive.sdk.actions.TapMessageFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.tapcentive.sdk.actions.TapMessageFragment.java

Source

/*
 * Copyright 2015 Tapcentive, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.tapcentive.sdk.actions;

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

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.widget.RelativeLayout;

import com.neopixl.pixlui.components.button.Button;
import com.neopixl.pixlui.components.textview.TextView;
import com.tapcentive.sdk.R;
import com.tapcentive.sdk.TapcentiveLibrary;
import com.tapcentive.sdk.model.Reward;

/**
 * The Class TapMessageFragment creates a dynamic and optimized view
 * based approach of the slots game in portrait mode and uses the Icons from
 * the reward list as the Icons for the spinning reels
 */
public class TapMessageFragment extends TapcentiveActionFragment {

    private static TapMessageFragment _fragment;

    /** The tag. */
    private static String TAG = "TapMessageFragment";

    /** The game view. */
    private View gameView;

    /** indicates whether the view has been created by the 
     * Main Activity */
    private boolean fragmentCreated = false;

    /** used to calculate size of reels and positioning within the view */
    private int usableHeight;

    /**
     * New instance.
     * 
     * @return the tap message fragment
     */
    public static TapMessageFragment newInstance() {
        _fragment = new TapMessageFragment();
        Bundle args = new Bundle();

        _fragment.setArguments(args);
        return _fragment;
    }

    /**
     * Instantiates a new tap message fragment.
     */
    public TapMessageFragment() {

    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Fragment#onCreateView(android.view.LayoutInflater,
     * android.view.ViewGroup, android.os.Bundle)
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_tap_message, parent, false);
        this.gameView = view;
        return view;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Fragment#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        fragmentCreated = true;
        // Always request a change to orientation in the event that a landscape type game
        // occupies the current view
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

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

        Log.d(TAG, "====> Message Fragment View - configuration changed");
        // If waiting for a configuration change, display the view again
        onResume();
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Fragment#onResume()
     */
    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "====> Message Fragment resumed");

        // Determines the current display metrics of the view - width, height etc.
        getDisplayMetrics();

        // If the fragment has not just been created from the main activity, don't try and
        // replay the game.
        if (!fragmentCreated) {
            return;
        }

        Log.d(TAG, "====> Message: Trying to Start Game.");
        if (isAdded() && getActivity() != null) {
            // Setup and starts the game      
            int orientation = getActivity().getResources().getConfiguration().orientation;
            // If orientation is not portrait, game play does not start and it waits for onConfigurationChange to occur.
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                Log.d(TAG, "====> Message: Start Game");

                // Game will not be replayed until fragment is actually created again
                fragmentCreated = false;
                startGame(this.gameView);
            } else {
                Log.d(TAG, "=======> Message - game not played onResume, orientation is not portrait");
            }
        } else {
            Log.d(TAG, "=======> Message  - game not played onResume, not added or activity is null");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "====> Message Fragment destroyed");
    }

    /**
     * Setup and starts the game.
     * 
     * @param view
     *            the game view the game is displayed on
     */
    private void startGame(View view) {
        // Get the current reward
        Reward reward = getCurrentReward();

        // If reward is found we can launch the game
        if (reward != null) {
            TapcentiveLibrary.getInstance().setTapInProcess(false);
            // Initialize the winning view
            initializeWinningLayout(view, usableHeight);

            // Starts game animation
            animateGame(view);
        }
    }

    /**
     * Initialize winning layout.
     * 
     * @param view
     *            the view
     * @param y
     *            the y coordinate
     */
    private void initializeWinningLayout(View view, int y) {
        // Setup the winning layout to be offscreeen
        RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.winning_layout_portrait);
        layout.setY(y);
        layout.getLayoutParams().height = usableHeight;

        // Populate all elements of the winning layout (bitmap, text...)
        initializeWinningLayoutWithReward(view, getCurrentReward());

        // Configure the callback when the "more rewards" button is pressed
        Button tapMessageButton = (Button) view.findViewById(R.id.tap_message_button_portrait);
        tapMessageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callback.onTapcentiveInteractionCompleted(_fragment);
            }
        });
    }

    /**
     * Initialize winning layout with reward.
     * 
     * @param view
     *            the view
     * @param reward
     *            the reward
     */
    private void initializeWinningLayoutWithReward(View view, Reward reward) {
        if (reward != null) {
            TextView headerText = (TextView) view.findViewById(R.id.winning_header_portrait);
            headerText.setText(reward.getTitle());
        }
    }

    /**
     * Animate the game.
     * 
     * @param view
     *            the view
     * @param gameLayout
     *            the game layout to animate
     * @param duration
     *            the duration of the animation in ms
     */
    @SuppressLint("NewApi")
    private void animateGame(final View view) {
        // stop screen from sleeping
        getActivity().getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.winning_layout_portrait);
        ViewPropertyAnimator animator = layout.animate();
        animator.translationYBy(-(1 + usableHeight)).setDuration(200);

        animator.setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                TapcentiveLibrary.getInstance().setAnimatedWhenStopped(false);
                TapcentiveLibrary.getInstance().setAnimationInProcess(false);
            }
        });
    }

    /**
     * Gets the current reward.
     * 
     * @return the current reward
     */
    private Reward getCurrentReward() {
        Reward reward = new Reward();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String play_result = prefs.getString("play_result", "");
        JSONObject result = null;
        try {
            result = new JSONObject(play_result);
        } catch (JSONException e) {
            Log.e(TAG, "Unable to parse JSON response: " + play_result);
            result = null;
        }
        String title = null;
        if (result != null) {
            try {
                title = result.getJSONObject("result").getJSONObject("reward_information").getJSONObject("tier")
                        .get("short_description").toString();
            } catch (JSONException e) {
                Log.e(TAG, "Unable to get short_description from JSON response");
            }
        }
        reward.setTitle(title);

        return reward;
    }

    /**
     * Gets the display metrics.
     * 
     * @return the display metrics
     */
    private void getDisplayMetrics() {
        // determine the screen size used for the animation
        DisplayMetrics dimension = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dimension);
        TypedValue tv = new TypedValue();
        getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
        int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId);
        int statusBarHeight = getResources()
                .getDimensionPixelSize(getResources().getIdentifier("status_bar_height", "dimen", "android"));

        usableHeight = dimension.heightPixels - (actionBarHeight + statusBarHeight);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.tapcentive.sdk.actions.TapcentiveActionFragment#onAnimationEnd(android
     * .animation.Animator)
     */
    @Override
    public void onAnimationEnd(Animator animator) {
        Log.d(TAG, "got onAnimationEnd event");

        TapcentiveLibrary.getInstance().setAnimatedWhenStopped(false);
        TapcentiveLibrary.getInstance().setAnimationInProcess(false);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.animation.Animator.AnimatorListener#onAnimationCancel(android
     * .animation.Animator)
     */
    public void onAnimationCancel(Animator animator) {
        Log.d(TAG, "got onAnimationCancel event");
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.animation.Animator.AnimatorListener#onAnimationStart(android.
     * animation.Animator)
     */
    public void onAnimationStart(Animator animator) {
        Log.d(TAG, "got onAnimationStart event");
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.animation.Animator.AnimatorListener#onAnimationRepeat(android
     * .animation.Animator)
     */
    public void onAnimationRepeat(Animator animator) {
        Log.d(TAG, "got onAnimationRepeat event");
    }

}