Currently, in my project, I have two files. A MainActivity.java(package com.example.AdTester;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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.AdView;
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.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
public class MainActivity extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
public static final String REWARD_AD_UNIT_ID="ca-app-pub-3940256099942544/5224354917";
public int amount = 0;
private RewardedAd mRewardedAd;
private TextView mTextView;
String text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadAmount();
mTextView=findViewById(R.id.Coins);
Button mButton = findViewById(R.id.RewardedbtnAds);
text = getResources().getString(R.string.coins_message, amount);
mTextView.setText(text);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(@NonNull InitializationStatus initializationStatus) {
}
});
loadRewardedAds();
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showRewardAds();
loadRewardedAds();
}
});
}
private void showRewardAds() {
if (mRewardedAd!=null) {
mRewardedAd.show(MainActivity.this, new OnUserEarnedRewardListener() {
@Override
public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
amount += rewardItem.getAmount();
text = getResources().getString(R.string.coins_message, amount);
mTextView.setText(text);
saveAmount();
}
});
} else {
Toast.makeText(MainActivity.this,"Reward ads is not ready yet", Toast.LENGTH_SHORT).show();
}
}
private void loadRewardedAds() {
AdRequest RewardedAdRequest1=new AdRequest.Builder().build();
RewardedAd.load(this, REWARD_AD_UNIT_ID, RewardedAdRequest1, new RewardedAdLoadCallback() {
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
mRewardedAd=null;
}
@Override
public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
super.onAdLoaded(rewardedAd);
mRewardedAd=rewardedAd;
rewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdClicked() {
super.onAdClicked();
}
@Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
}
@Override
public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
}
@Override
public void onAdImpression() {
super.onAdImpression();
}
@Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
}
});
}
});
final boolean[] volt = {false};
AdView mAdView = findViewById(R.id.adView);
AdRequest BannerAdRequest = new AdRequest.Builder().build();
Button bannerbutton = findViewById(R.id.BannerbtnAds);
bannerbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!volt[0]) {
mAdView.loadAd(BannerAdRequest);
mAdView.setVisibility(View.VISIBLE);
volt[0] = true;
} else {
mAdView.setVisibility(View.GONE);
volt[0] = false;
}
}
});
loadInterstitialAd(); // Call this method to load the ad
Button button = findViewById(R.id.IntbtnAds);
button.setOnClickListener(view -> {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn’t ready yet.");
loadInterstitialAd(); // Try to load again if it wasn’t ready when the button was clicked
}
});
Button resetButton = findViewById(R.id.resetButton);
resetButton.setOnClickListener(view -> {
amount = 0;
saveAmount();
text = getResources().getString(R.string.coins_message, amount);
mTextView.setText(text);
});
}
private void loadInterstitialAd() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
setInterstitialAdCallbacks();
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
}
});
}
private void setInterstitialAdCallbacks() {
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
@Override
public void onAdDismissedFullScreenContent() {
mInterstitialAd = null;
loadInterstitialAd(); // Load a new ad when the current one is closed
}
@Override
public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
mInterstitialAd = null;
}
// Implement other callbacks if needed
});
}
private void saveAmount() {
SharedPreferences sharedPreferences = getSharedPreferences("UserPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("coinsAmount", amount);
editor.apply();
}
private void loadAmount() {
SharedPreferences sharedPreferences = getSharedPreferences("UserPreferences", MODE_PRIVATE);
amount = sharedPreferences.getInt("coinsAmount", 0);
}
private void resetCoins() {
Button button = findViewById(R.id.IntbtnAds);
button.setOnClickListener(view -> {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn’t ready yet.");
loadInterstitialAd(); // Try to load again if it wasn’t ready when the button was clicked
}
});
}
}) and a MyApplication.java(package com.example.AdTester;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;
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.appopen.AppOpenAd;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import java.util.Date;
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks, LifecycleObserver {
private AppOpenAdManager appOpenAdManager;
private Activity currentActivity;
public long loadTime = 0;
@Override
public void onCreate() {
super.onCreate();
MobileAds.initialize(
this,
new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
appOpenAdManager = new AppOpenAdManager(this);
registerActivityLifecycleCallbacks(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
protected void onMoveToForeground() {
// Show the ad (if available) when the app moves to foreground.
appOpenAdManager.showAdIfAvailable(currentActivity);
}
public class AppOpenAdManager {
private boolean isFirstLaunch = true;
private Context applicationContext; // Store the Application context
public AppOpenAdManager(Context context) {
this.applicationContext = context.getApplicationContext(); // Store the application context to avoid NPE
loadAd(applicationContext);
}
private static final String LOG_TAG = "AppOpenAdManager";
private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921";
private AppOpenAd appOpenAd = null;
private boolean isLoadingAd = false;
private boolean isShowingAd = false;
/** Constructor. */
public AppOpenAdManager(MyApplication myApplication) {}
/** Request an ad. */
private void loadAd(Context context) {
// We will implement this below.
if (isLoadingAd || isAdAvailable()) {
return;
}
isLoadingAd = true;
AdRequest request = new AdRequest.Builder().build();
AppOpenAd.load(
context, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
new AppOpenAd.AppOpenAdLoadCallback() {
@Override
public void onAdLoaded(AppOpenAd ad) {
// Called when an app open ad has loaded.
Log.d(LOG_TAG, "Ad was loaded.");
appOpenAd = ad;
isLoadingAd = false;
loadTime = (new Date()).getTime();
if(isFirstLaunch) {
showAdIfAvailable(currentActivity);
isFirstLaunch = false;
}
}
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
// Called when an app open ad has failed to load.
Log.d(LOG_TAG, loadAdError.getMessage());
isLoadingAd = false;
}
});
}
public void showAdIfAvailable(
@NonNull final Activity activity){
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(LOG_TAG, "The app open ad is already showing.");
return;
}
// If the app open ad is not available yet, invoke the callback then load the ad.
if (!isAdAvailable()) {
Log.d(LOG_TAG, "The app open ad is not ready yet.");
loadAd(MyApplication.this);
return;
}
appOpenAd.setFullScreenContentCallback(
new FullScreenContentCallback (){
@Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, "Ad dismissed fullscreen content.");
appOpenAd = null;
isShowingAd = false;
loadAd(activity);
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, adError.getMessage());
appOpenAd = null;
isShowingAd = false;
loadAd(activity);
}
@Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d(LOG_TAG, "Ad showed fullscreen content.");
}
});
isShowingAd = true;
appOpenAd.show(activity);
}
/** Check if ad exists and can be shown. */
private boolean isAdAvailable() {
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}
}
private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
long dateDifference = (new Date()).getTime() - this.loadTime;
long numMilliSecondsPerHour = 3600000;
return (dateDifference < (numMilliSecondsPerHour * numHours));
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityStarted(Activity activity) {
// Updating the currentActivity only when an ad is not showing.
if (!appOpenAdManager.isShowingAd) {
currentActivity = activity;
}
}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
@Override
public void onActivityDestroyed(Activity activity) {}
})
I'm new to Android app developement. Can you please explain me, how does these two files link together? So when does each start to run?
And can you please explain the basic concept of classes? I've only programmed in C before, so this is new to me.
Please explain the classes (if those two different Java files are called classes) in a way that a that a small kid would understand, so please be clear.