09-22-2024, 03:12 AM
(This post was last modified: 09-22-2024, 03:14 AM by Progromatic Admin.)
Add the dependencies for the Google Mobile Ads SDK to your app-level build file:
Add your AdMob app ID, as identified in the AdMob web interface, to your app's AndroidManifest.xml file. To do so, add a <meta-data> tag with android:name="com.google.android.gms.ads.APPLICATION_ID". You can find your app ID in the AdMob web interface. For android:value, insert your own AdMob app ID, surrounded by quotation marks.
now we start with codes
first we need to create java class
class name is " GoogleMobileAdsConsentManager "
change
package com.example.appname;
to yours
then we add in layout .xml
finally MainActivity like below
Code:
dependencies {
implementation("com.google.android.gms:play-services-ads:23.3.0")
}
Code:
<manifest>
<application>
<!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
</application>
</manifest>
now we start with codes
first we need to create java class
class name is " GoogleMobileAdsConsentManager "
change
package com.example.appname;
to yours
Code:
/*
* Copyright 2023 Google LLC
*
* 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.example.appname;
import android.app.Activity;
import android.content.Context;
import com.google.android.ump.ConsentDebugSettings;
import com.google.android.ump.ConsentForm.OnConsentFormDismissedListener;
import com.google.android.ump.ConsentInformation;
import com.google.android.ump.ConsentInformation.PrivacyOptionsRequirementStatus;
import com.google.android.ump.ConsentRequestParameters;
import com.google.android.ump.FormError;
import com.google.android.ump.UserMessagingPlatform;
/**
* The Google Mobile Ads SDK provides the User Messaging Platform (Google's IAB Certified consent
* management platform) as one solution to capture consent for users in GDPR impacted countries.
* This is an example and you can choose another consent management platform to capture consent.
*/
public class GoogleMobileAdsConsentManager {
private static GoogleMobileAdsConsentManager instance;
private final ConsentInformation consentInformation;
/** Private constructor */
private GoogleMobileAdsConsentManager(Context context) {
this.consentInformation = UserMessagingPlatform.getConsentInformation(context);
}
/** Public constructor */
public static GoogleMobileAdsConsentManager getInstance(Context context) {
if (instance == null) {
instance = new GoogleMobileAdsConsentManager(context);
}
return instance;
}
/** Interface definition for a callback to be invoked when consent gathering is complete. */
public interface OnConsentGatheringCompleteListener {
void consentGatheringComplete(FormError error);
}
/** Helper variable to determine if the app can request ads. */
public boolean canRequestAds() {
return consentInformation.canRequestAds();
}
/** Helper variable to determine if the privacy options form is required. */
public boolean isPrivacyOptionsRequired() {
return consentInformation.getPrivacyOptionsRequirementStatus()
== PrivacyOptionsRequirementStatus.REQUIRED;
}
/**
* Helper method to call the UMP SDK methods to request consent information and load/present a
* consent form if necessary.
*/
public void gatherConsent(
Activity activity, OnConsentGatheringCompleteListener onConsentGatheringCompleteListener) {
// For testing purposes, you can force a DebugGeography of EEA or NOT_EEA.
ConsentDebugSettings debugSettings =
new ConsentDebugSettings.Builder(activity)
// .setDebugGeography(ConsentDebugSettings.DebugGeography.DEBUG_GEOGRAPHY_EEA)
.addTestDeviceHashedId(MainActivity.TEST_DEVICE_HASHED_ID)
.build();
ConsentRequestParameters params =
new ConsentRequestParameters.Builder().setConsentDebugSettings(debugSettings).build();
// Requesting an update to consent information should be called on every app launch.
consentInformation.requestConsentInfoUpdate(
activity,
params,
() ->
UserMessagingPlatform.loadAndShowConsentFormIfRequired(
activity,
formError -> {
// Consent has been gathered.
onConsentGatheringCompleteListener.consentGatheringComplete(formError);
}),
requestConsentError ->
onConsentGatheringCompleteListener.consentGatheringComplete(requestConsentError));
}
/** Helper method to call the UMP SDK method to present the privacy options form. */
public void showPrivacyOptionsForm(
Activity activity, OnConsentFormDismissedListener onConsentFormDismissedListener) {
UserMessagingPlatform.showPrivacyOptionsForm(activity, onConsentFormDismissedListener);
}
}
then we add in layout .xml
Code:
<FrameLayout
android:id="@+id/ad_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true" />
finally MainActivity like below
Code:
package com.example.appname;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowMetrics;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuBuilder;
import androidx.appcompat.widget.SearchView;
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.ads.MobileAds;
import com.google.android.gms.ads.RequestConfiguration;
import com.google.android.gms.tasks.Task;
import com.google.android.play.core.review.ReviewInfo;
import com.google.android.play.core.review.ReviewManager;
import com.google.android.play.core.review.ReviewManagerFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
public class MainActivity extends AppCompatActivity {
private AdView adView;
private FrameLayout adContainerView;
public static final String TEST_DEVICE_HASHED_ID = "ABCDEF012345";
private GoogleMobileAdsConsentManager googleMobileAdsConsentManager;
private final AtomicBoolean isMobileAdsInitializeCalled = new AtomicBoolean(false);
private static final String TAG = "MyActivity";
private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/9214589741";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adContainerView = findViewById(R.id.ad_view_container);
// Log the Mobile Ads SDK version.
Log.d(TAG, "Google Mobile Ads SDK Version: " + MobileAds.getVersion());
googleMobileAdsConsentManager =
GoogleMobileAdsConsentManager.getInstance(getApplicationContext());
googleMobileAdsConsentManager.gatherConsent(
this,
consentError -> {
if (consentError != null) {
// Consent not obtained in current session.
Log.w(
TAG,
String.format("%s: %s", consentError.getErrorCode(), consentError.getMessage()));
}
if (googleMobileAdsConsentManager.canRequestAds()) {
initializeMobileAdsSdk();
}
if (googleMobileAdsConsentManager.isPrivacyOptionsRequired()) {
// Regenerate the options menu to include a privacy setting.
invalidateOptionsMenu();
}
});
// This sample attempts to load ads using consent obtained in the previous session.
if (googleMobileAdsConsentManager.canRequestAds()) {
initializeMobileAdsSdk();
}
}
/** Called when leaving the activity */
@Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called when returning to the activity */
@Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
/** Called before the activity is destroyed */
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
private void loadBanner() {
// [START create_ad_view]
// Create a new ad view.
adView = new AdView(this);
adView.setAdUnitId(AD_UNIT_ID);
adView.setAdSize(getAdSize());
// Replace ad container with new ad view.
adContainerView.removeAllViews();
adContainerView.addView(adView);
// [END create_ad_view]
// [START load_ad]
// Start loading the ad in the background.
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// [END load_ad]
}
private void initializeMobileAdsSdk() {
if (isMobileAdsInitializeCalled.getAndSet(true)) {
return;
}
// Set your test devices.
MobileAds.setRequestConfiguration(
new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList(TEST_DEVICE_HASHED_ID)).build());
new Thread(
() -> {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this, initializationStatus -> {});
// Load an ad on the main thread.
runOnUiThread(this::loadBanner);
})
.start();
}
// Get the ad size with screen width.
public AdSize getAdSize() {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int adWidthPixels = displayMetrics.widthPixels;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowMetrics windowMetrics = this.getWindowManager().getCurrentWindowMetrics();
adWidthPixels = windowMetrics.getBounds().width();
}
float density = displayMetrics.density;
int adWidth = (int) (adWidthPixels / density);
return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth);
}
}
Dev Abdulrahman Abdulwahab
I'm Web and Mobile Developer
Forum Admin and Store Admin
I'm Web and Mobile Developer
Forum Admin and Store Admin