티스토리 뷰

카테고리 없음

안드로이드 보상형 광고 만들기

뽀로로친구에디 2022. 7. 21. 20:27

 

AdDialogFragment.java

package com.jw.openadsexample;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.fragment.app.DialogFragment;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jw.openadsexample.R;

/**
 * A dialog fragment to inform the users about an upcoming interstitial video ad and let the user
 * click the cancel button to skip the ad. This fragment inflates the dialog_ad.xml layout.
 */
public class AdDialogFragment extends DialogFragment {

    /** Bundle argument's name for number of coins rewarded by watching an ad. */
    public static final String REWARD_AMOUNT = "rewardAmount";

    /** Bundle argument's name for the unit of the reward amount. */
    public static final String REWARD_TYPE = "rewardType";

    /** Number of seconds to count down before showing ads. */
    private static final long COUNTER_TIME = 5;

    /** A string that represents this class in the logcat. */
    private static final String TAG = "AdDialogFragment";

    /** A timer for counting down until showing ads. */
    private CountDownTimer countDownTimer;

    /** Number of remaining seconds while the count down timer runs. */
    private long timeRemaining;

    /** Delivers the events to the Main Activity when the user interacts with this dialog. */
    private AdDialogInteractionListener listener;

    /**
     * Creates an instance of the AdDialogFragment and sets reward information for its title.
     *
     * @param rewardAmount Number of coins rewarded by watching an ad.
     * @param rewardType The unit of the reward amount. For example: coins, tokens, life, etc.
     */
    public static AdDialogFragment newInstance(int rewardAmount, String rewardType) {
        AdDialogFragment fragment = new AdDialogFragment();
        Bundle args = new Bundle();
        args.putInt(REWARD_AMOUNT, rewardAmount);
        args.putString(REWARD_TYPE, rewardType);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Registers the callbacks to be invoked when the user interacts with this dialog. If there is no
     * user interactions, the dialog is dismissed and the user will see a video interstitial ad.
     *
     * @param listener The callbacks that will run when the user interacts with this dialog.
     */
    public void setAdDialogInteractionListener(AdDialogInteractionListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Inflate and set the layout for the dialog.
        // Pass null as the parent view because its going in the dialog layout.
        View view = requireActivity().getLayoutInflater().inflate(R.layout.dialog_ad, null);
        builder.setView(view);

        Bundle args = getArguments();
        int rewardAmount = -1;
        String rewardType = null;
        if (args != null) {
            rewardAmount = args.getInt(REWARD_AMOUNT);
            rewardType = args.getString(REWARD_TYPE);
        }
        if (rewardAmount > 0 && rewardType != null) {
            builder.setTitle(getString(R.string.more_coins_text, rewardAmount, rewardType));
        }

        builder.setNegativeButton(
                getString(R.string.negative_button_text),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        getDialog().cancel();
                    }
                });
        Dialog dialog = builder.create();
        createTimer(COUNTER_TIME, view);
        return dialog;
    }

    /**
     * Creates the a timer to count down until the rewarded interstitial ad.
     *
     * @param time Number of seconds to count down.
     * @param dialogView The view of this dialog for updating the remaining seconds count.
     */
    private void createTimer(long time, View dialogView) {
        final TextView textView = dialogView.findViewById(R.id.timer);
        countDownTimer =
                new CountDownTimer(time * 1000, 50) {
                    @Override
                    public void onTick(long millisUnitFinished) {
                        timeRemaining = ((millisUnitFinished / 1000) + 1);
                        textView.setText(
                                String.format(getString(R.string.video_starting_in_text), timeRemaining));
                    }

                    /** Called when the count down finishes and the user hasn't cancelled the dialog. */
                    @Override
                    public void onFinish() {
                        getDialog().dismiss();

                        if (listener != null) {
                            Log.d(TAG, "onFinish: Calling onShowAd().");
                            listener.onShowAd();
                        }
                    }
                };
        countDownTimer.start();
    }

    /** Called when the user clicks the "No, Thanks" button or press the back button. */
    @Override
    public void onCancel(@NonNull DialogInterface dialog) {
        super.onCancel(dialog);
        if (listener != null) {
            Log.d(TAG, "onCancel: Calling onCancelAd().");
            listener.onCancelAd();
        }
    }

    /** Called when the fragment is destroyed. */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: Cancelling the timer.");
        countDownTimer.cancel();
        countDownTimer = null;
    }

    /** Callbacks when the user interacts with this dialog. */
    public interface AdDialogInteractionListener {

        /** Called when the timer finishes without user's cancellation. */
        void onShowAd();

        /** Called when the user clicks the "No, thanks" button or press the back button. */
        void onCancelAd();
    }
}

 

MainActivity.java

package com.jw.openadsexample;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd;
import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAdLoadCallback;

public class MainActivity extends AppCompatActivity {

    private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/5354046379";
    private static final long COUNTER_TIME = 10;
    private static final int GAME_OVER_REWARD = 1;
    private static final String TAG = "MainActivity";

    private int coinCount;
    private TextView coinCountText;
    private CountDownTimer countDownTimer;
    private boolean gameOver;
    private boolean gamePaused;


    private RewardedInterstitialAd rewardedInterstitialAd;
    private Button retryButton;
    private long timeRemaining;
    boolean isLoadingAds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MobileAds.initialize(
                this,
                new OnInitializationCompleteListener() {
                    @Override
                    public void onInitializationComplete(InitializationStatus initializationStatus) {
                        loadRewardedInterstitialAd();
                    }
                });

        // Create the "retry" button, which tries to show a rewarded ad between game plays.
        retryButton = findViewById(R.id.retry_button);
        retryButton.setVisibility(View.INVISIBLE);
        retryButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startGame();
                    }
                });




        // Display current coin count to user.
        coinCountText = findViewById(R.id.coin_count_text);
        coinCount = 0;
        coinCountText.setText("Coins: " + coinCount);

        startGame();
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseGame();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!gameOver && gamePaused) {
            resumeGame();
        }
    }

    private void pauseGame() {
        countDownTimer.cancel();
        gamePaused = true;
    }

    private void resumeGame() {
        createTimer(timeRemaining);
        gamePaused = false;
    }

    private void loadRewardedInterstitialAd() {
        if (rewardedInterstitialAd == null) {
            isLoadingAds = true;

            AdRequest adRequest = new AdRequest.Builder().build();
            // Use the test ad unit ID to load an ad.
            RewardedInterstitialAd.load(
                    MainActivity.this,
                    AD_UNIT_ID,
                    adRequest,
                    new RewardedInterstitialAdLoadCallback() {
                        @Override
                        public void onAdLoaded(RewardedInterstitialAd ad) {
                            Log.d(TAG, "onAdLoaded");

                            rewardedInterstitialAd = ad;
                            isLoadingAds = false;
                            Toast.makeText(MainActivity.this, "onAdLoaded", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onAdFailedToLoad(LoadAdError loadAdError) {
                            Log.d(TAG, "onAdFailedToLoad: " + loadAdError.getMessage());

                            // Handle the error.
                            rewardedInterstitialAd = null;
                            isLoadingAds = false;
                            Toast.makeText(MainActivity.this, "onAdFailedToLoad", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }

    private void addCoins(int coins) {
        coinCount += coins;
        coinCountText.setText("Coins: " + coinCount);
    }

    private void startGame() {
        // Hide the retry button, load the ad, and start the timer.
        retryButton.setVisibility(View.INVISIBLE);

        if (rewardedInterstitialAd != null && !isLoadingAds) {
            loadRewardedInterstitialAd();
        }
        createTimer(COUNTER_TIME);
        gamePaused = false;
        gameOver = false;
    }

    // Create the game timer, which counts down to the end of the level
    // and shows the "retry" button.
    private void createTimer(long time) {
        final TextView textView = findViewById(R.id.timer);
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        countDownTimer =
                new CountDownTimer(time * 1000, 50) {
                    @Override
                    public void onTick(long millisUnitFinished) {
                        timeRemaining = ((millisUnitFinished / 1000) + 1);
                        textView.setText("seconds remaining: " + timeRemaining);
                    }

                    @Override
                    public void onFinish() {
                        textView.setText("You Lose!");
                        addCoins(GAME_OVER_REWARD);
                        retryButton.setVisibility(View.VISIBLE);

                        gameOver = true;

                        if (rewardedInterstitialAd == null) {
                            Log.d(TAG, "The rewarded interstitial ad is not ready.");
                            return;
                        }

                        RewardItem rewardItem = rewardedInterstitialAd.getRewardItem();
                        int rewardAmount = rewardItem.getAmount();
                        String rewardType = rewardItem.getType();

                        Log.d(TAG, "The rewarded interstitial ad is ready.");
                        introduceVideoAd(rewardAmount, rewardType);
                    }
                };
        countDownTimer.start();
    }

    private void introduceVideoAd(int rewardAmount, String rewardType) {
        AdDialogFragment dialog = AdDialogFragment.newInstance(rewardAmount, rewardType);
        dialog.setAdDialogInteractionListener(
                new AdDialogFragment.AdDialogInteractionListener() {
                    @Override
                    public void onShowAd() {
                        Log.d(TAG, "The rewarded interstitial ad is starting.");

                        showRewardedVideo();
                    }

                    @Override
                    public void onCancelAd() {
                        Log.d(TAG, "The rewarded interstitial ad was skipped before it starts.");
                    }
                });
        dialog.show(getSupportFragmentManager(), "AdDialogFragment");
    }

    private void showRewardedVideo() {

        if (rewardedInterstitialAd == null) {
            Log.d(TAG, "The rewarded interstitial ad wasn't ready yet.");
            return;
        }

        rewardedInterstitialAd.setFullScreenContentCallback(
                new FullScreenContentCallback() {
                    /** Called when ad showed the full screen content. */
                    @Override
                    public void onAdShowedFullScreenContent() {
                        Log.d(TAG, "onAdShowedFullScreenContent");

                        Toast.makeText(MainActivity.this, "onAdShowedFullScreenContent", Toast.LENGTH_SHORT)
                                .show();
                    }

                    /** Called when the ad failed to show full screen content. */
                    @Override
                    public void onAdFailedToShowFullScreenContent(AdError adError) {
                        Log.d(TAG, "onAdFailedToShowFullScreenContent: " + adError.getMessage());

                        // Don't forget to set the ad reference to null so you
                        // don't show the ad a second time.
                        rewardedInterstitialAd = null;
                        loadRewardedInterstitialAd();

                        Toast.makeText(
                                MainActivity.this, "onAdFailedToShowFullScreenContent", Toast.LENGTH_SHORT)
                                .show();
                    }

                    /** Called when full screen content is dismissed. */
                    @Override
                    public void onAdDismissedFullScreenContent() {
                        // Don't forget to set the ad reference to null so you
                        // don't show the ad a second time.
                        rewardedInterstitialAd = null;
                        Log.d(TAG, "onAdDismissedFullScreenContent");
                        Toast.makeText(MainActivity.this, "onAdDismissedFullScreenContent", Toast.LENGTH_SHORT)
                                .show();
                        // Preload the next rewarded interstitial ad.
                        loadRewardedInterstitialAd();
                    }
                });

        Activity activityContext = MainActivity.this;
        rewardedInterstitialAd.show(
                activityContext,
                new OnUserEarnedRewardListener() {
                    @Override
                    public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                        // Handle the reward.
                        Log.d(TAG, "The user earned the reward.");
                        addCoins(rewardItem.getAmount());
                    }
                });
    }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/game_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/impossible_game"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_marginTop="50dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <TextView
        android:id="@+id/timer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@id/game_title"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />

    <Button
        android:id="@+id/retry_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        app:layout_constraintTop_toBottomOf="@id/timer"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:text="@string/retry_button_text" />




    <TextView
        android:id="@+id/coin_count_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:text="@string/default_coin_text"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

dialog_ad.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:id="@+id/timer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp" />
</LinearLayout>

 

strings.xml

<resources>
    <string name="app_name" translatable="false">AdMob Rewarded Interstitial Example</string>
    <string name="action_settings" translatable="false">Settings</string>
    <string name="impossible_game" translatable="false">Impossible Game</string>
    <string name="retry_button_text" translatable="false">Retry</string>
    <string name="default_coin_text" translatable="false">Coins: 0</string>
    <string name="more_coins_text" translatable="false">Watch an ad for %d more %s.</string>
    <string name="video_starting_in_text" translatable="false">Video starting in %d…</string>
    <string name="negative_button_text" translatable="false">No, thanks</string>
</resources>
댓글
최근에 달린 댓글
글 보관함
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Total
Today
Yesterday
    뽀로로친구에디
    최근에 올라온 글