Untuk jenis iklan App open, anda harus menambhakan beberapa pengaturan sebagai berikut:
A. Menambah dependencies lifecycle di build.gradle(App)
dependencies {
implementation 'androidx.lifecycle:lifecycle-process:2.7.0'
}
B. Membuat class MyAplication
import android.app.Application;
import android.content.Context;
public class MyApplication extends Application {
private static OpenAds alienOpenAds;
Context context;
//Uranus
@Override
public void onCreate() {
super.onCreate();
context = this;
alienOpenAds = new OpenAds(this);
}
}
C. Memanggil MyApplication ke manifest
<application
android:name=".MyApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AlienProps"
tools:targetApi="31">
D. Membuat class OpenAds
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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.appopen.AppOpenAd;
import java.util.Date;
public class OpenAds implements LifecycleObserver, Application.ActivityLifecycleCallbacks {
public static String openAppId ="";
public static MyApplication myApplication;
public static AppOpenAdManager appOpenAdManager;
public static Activity currentActivity;
public static boolean LOADADS;
public OpenAds(MyApplication myApplication) {
OpenAds.myApplication = myApplication;
OpenAds.myApplication.registerActivityLifecycleCallbacks(this);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
private static AdRequest getAdRequest() {
return new AdRequest.Builder().build();
}
public static void LoadOpenAds(String idOpenAds) {
try {
openAppId = idOpenAds;
} catch (Exception e) {
e.printStackTrace();
}
}
/** LifecycleObserver method that shows the app open ad when the app moves to foreground. */
@OnLifecycleEvent(Lifecycle.Event.ON_START)
protected void onMoveToForeground() {
// Show the ad (if available) when the app moves to foreground.
appOpenAdManager.showAdIfAvailable(currentActivity);
}
/** ActivityLifecycleCallback methods. */
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {}
@Override
public void onActivityStarted(@NonNull Activity activity) {
// An ad activity is started when an ad is showing, which could be AdActivity class from Google
// SDK or another activity class implemented by a third party mediation partner. Updating the
// currentActivity only when an ad is not showing will ensure it is not an ad activity, but the
// one that shows the ad.
if (!appOpenAdManager.isShowingAd) {
currentActivity = activity;
}
}
@Override
public void onActivityResumed(@NonNull Activity activity) {}
@Override
public void onActivityPaused(@NonNull Activity activity) {}
@Override
public void onActivityStopped(@NonNull Activity activity) {}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {}
/**
* Interface definition for a callback to be invoked when an app open ad is complete
* (i.e. dismissed or fails to show).
*/
public interface OnShowAdCompleteListener {
void onShowAdComplete();
}
/** Inner class that loads and shows app open ads. */
public static class AppOpenAdManager {
private static final String LOG_TAG = "AppOpenAdManager";
public static AppOpenAd appOpenAd = null;
private static boolean isLoadingAd = false;
private static boolean isShowingAd = false;
/** Keep track of the time an app open ad is loaded to ensure you don't show an expired ad. */
private static long loadTime = 0;
/** Constructor. */
public AppOpenAdManager() {}
/**
* Load an ad.
*
* @param context the context of the activity that loads the ad
*/
public static void loadAd(Context context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
return;
}
isLoadingAd = true;
AdRequest request = new AdRequest.Builder().build();
AppOpenAd.load(
context,
openAppId,
request,
new AppOpenAd.AppOpenAdLoadCallback() {
/**
* Called when an app open ad has loaded.
*
* @param ad the loaded app open ad.
*/
@Override
public void onAdLoaded(AppOpenAd ad) {
appOpenAd = ad;
isLoadingAd = false;
loadTime = (new Date()).getTime();
Log.d(LOG_TAG, "onAdLoaded.");
}
/**
* Called when an app open ad has failed to load.
*
* @param loadAdError the error.
*/
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
isLoadingAd = false;
Log.d(LOG_TAG, "onAdFailedToLoad: " + loadAdError.getMessage());
}
});
}
/** Check if ad was loaded more than n hours ago. */
private static boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
long dateDifference = (new Date()).getTime() - loadTime;
long numMilliSecondsPerHour = 3600000;
return (dateDifference < (numMilliSecondsPerHour * numHours));
}
/** Check if ad exists and can be shown. */
private static boolean isAdAvailable() {
// Ad references in the app open beta will time out after four hours, but this time limit
// may change in future beta versions. For details, see:
// https://support.google.com/admob/answer/9341964?hl=en
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad
*/
public static void showAdIfAvailable(@NonNull final Activity activity) {
showAdIfAvailable(
activity,
new OnShowAdCompleteListener() {
@Override
public void onShowAdComplete() {
}
});
}
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad
* @param onShowAdCompleteListener the listener to be notified when an app open ad is complete
*/
public static void showAdIfAvailable(
@NonNull final Activity activity,
@NonNull OnShowAdCompleteListener onShowAdCompleteListener) {
// 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.");
onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
return;
}
Log.d(LOG_TAG, "Will show ad.");
appOpenAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
/** Called when full screen content is dismissed. */
@Override
public void onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable() returns false.
appOpenAd = null;
isShowingAd = false;
Log.d(LOG_TAG, "onAdDismissedFullScreenContent.");
onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
}
/** Called when fullscreen content failed to show. */
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
appOpenAd = null;
isShowingAd = false;
Log.d(LOG_TAG, "onAdFailedToShowFullScreenContent: " + adError.getMessage());
onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
}
/** Called when fullscreen content is shown. */
@Override
public void onAdShowedFullScreenContent() {
Log.d(LOG_TAG, "onAdShowedFullScreenContent.");
}
});
isShowingAd = true;
appOpenAd.show(activity);
}
}
}
E. Memanggil iklan OpenAds di halaman pembuka (contoh SplashActvity.java)
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
OpenAds.LoadOpenAds("testing_alien");
OpenAds.AppOpenAdManager.showAdIfAvailable(SplashActivity.this, new OpenAds.OnShowAdCompleteListener() {
@Override
public void onShowAdComplete() {
//Kondisi iklan Open App selesai dibuka
startActivity(true);
}
});
}
private void startActivity(boolean useTime){
if (useTime){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
},1000*3);
}else {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}
}