How to resolve Warning W/OkHttpClient: A connection to https://googleads… was leaked. Did you forget to close a response body?

  android, java

I have a challenge and it got involved with restricted adServing while trying to implement interstitial ads with recent SDK 19.7.0. I used AdManager class to serve interstitial ads and call it where I want in the App activity but I kept receiving a warning indicating that I forgot to close a response body. I ignored it but it got involved with restricted Adserving.
Please coders I need your help. I will show below all the ad formats I implored in the help for you to help me check. Thanks a lot.

This is Manifests

<application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:grantUriPermissions="true"
        android:requestLegacyExternalStorage="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!-- 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-3940256099942544~3347511713"/>
        
        <activity android:name=".NewActivity0"/>

        .
        .
        .
        .
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

       

    </application>

This is AdsManager.java class for Interstitial

public class AdsManager {
    private static InterstitialAd mInterstitialAd;
    private Context ctx;
    //INTERSTITIAL TST ID = ca-app-pub-3940256099942544/1033173712
    private static final String AD_UNIT_ID_FOR_INTERSTITIAL = "ca-app-pub-3940256099942544/1033173712";

    public AdsManager(Context ctx)
    {
        this.ctx = ctx;

        MobileAds.initialize(ctx, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {

            }
        });
    }



    public InterstitialAd createInterstitialAds() {
        AdRequest adRequest = new AdRequest.Builder().build();
        InterstitialAd.load(ctx,AD_UNIT_ID_FOR_INTERSTITIAL, adRequest, new InterstitialAdLoadCallback() {
            @Override
            public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                // The mInterstitialAd reference will be null until
                // an ad is loaded.
                mInterstitialAd = interstitialAd;
                Log.d("---Admob", "onAdLoaded");
                mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
                    @Override
                    public void onAdDismissedFullScreenContent() {
                        // Called when fullscreen content is dismissed.
                        Log.d("---Admob", "The ad was dismissed.");

                        //Here I can call the ads to show within activity or Use Intent and send to second activity.
                        //E.g
                        //Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                        //                    startActivity(intent);

                    }

                    @Override
                    public void onAdFailedToShowFullScreenContent(AdError adError) {
                        // Called when fullscreen content failed to show.
                        Log.d("---Admob", "The ad failed to show.");
                    }

                    @Override
                    public void onAdShowedFullScreenContent() {
                        // Called when fullscreen content is shown.
                        // Make sure to set your reference to null so you don't
                        // show it a second time.
                        mInterstitialAd = null;
                        Log.d("---Admob", "The ad was shown.");
                    }
                });
            }

            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                // Handle the error
                Log.d("---Admob", loadAdError.getMessage());
                mInterstitialAd = null;
            }
        });
        return null;
    }

    public InterstitialAd getInterstitialAd(){
        return mInterstitialAd;

    }

    public void createAds(AdView adView){

        AdRequest adRequest = new AdRequest.Builder().build();
        adView.setAdListener(new AdListener(){

            @Override
            public void onAdFailedToLoad(LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                Toast.makeText(ctx, ""+loadAdError.getCode(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                Toast.makeText(ctx, "ads is loaded", Toast.LENGTH_SHORT).show();
            }
        });
        adView.loadAd(adRequest);
    }



}

This is AppOpenManager.java class for Open Ads

public class AppOpenManager implements LifecycleObserver, Application.ActivityLifecycleCallbacks {
    private static final String LOG_TAG = "AppOpenManager";
    //BANNER TST ID = ca-app-pub-3940256099942544/3419835294
    private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/3419835294";
    private static boolean isShowingAd = false;
    private final MyApplication myApplication;
    private Activity currentActivity;
    private AppOpenAd appOpenAd = null;
    private long loadTime = 0;
    private AppOpenAd.AppOpenAdLoadCallback loadCallback;

    /**
     * Constructor
     */
    public AppOpenManager(MyApplication myApplication) {
        this.myApplication = myApplication;
        this.myApplication.registerActivityLifecycleCallbacks(this);
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    /**
     * LifecycleObserver methods
     */
    @OnLifecycleEvent(ON_START)
    public void onStart() {
        showAdIfAvailable();
        Log.d(LOG_TAG, "onStart");
    }

    /**
     * Shows the ad if one isn't already showing.
     */
    public void showAdIfAvailable() {
        // Only show ad if there is not already an app open ad currently showing
        // and an ad is available.
        if (!isShowingAd && isAdAvailable()) {
            Log.d(LOG_TAG, "Will show ad.");

            FullScreenContentCallback fullScreenContentCallback =
                    new FullScreenContentCallback() {
                        @Override
                        public void onAdDismissedFullScreenContent() {
                            // Set the reference to null so isAdAvailable() returns false.
                            AppOpenManager.this.appOpenAd = null;
                            isShowingAd = false;
                            fetchAd();
                        }

                        @Override
                        public void onAdFailedToShowFullScreenContent(AdError adError) {
                        }

                        @Override
                        public void onAdShowedFullScreenContent() {
                            isShowingAd = true;
                        }
                    };

            appOpenAd.setFullScreenContentCallback(fullScreenContentCallback);
            appOpenAd.show(currentActivity);

        } else {
            Log.d(LOG_TAG, "Can not show ad.");
            fetchAd();
        }
    }

    /**
     * Request an ad
     */
    public void fetchAd() {
        // Have unused ad, no need to fetch another.
        if (isAdAvailable()) {
            return;
        }

        loadCallback =
                new AppOpenAd.AppOpenAdLoadCallback() {
                    @Override
                    public void onAdLoaded(@NonNull AppOpenAd appOpenAd) {
                        super.onAdLoaded(appOpenAd);
                        AppOpenManager.this.appOpenAd = appOpenAd;
                        AppOpenManager.this.loadTime = (new Date()).getTime();
                        Log.d(LOG_TAG, "App Open Ad Loaded");
                    }

                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                        super.onAdFailedToLoad(loadAdError);
                        Log.d(LOG_TAG, "Loading App Open Ad Failed");
                    }

                };
        AdRequest request = getAdRequest();
        AppOpenAd.load(
                myApplication, AD_UNIT_ID, request,
                AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, loadCallback);
    }

    /**
     * Utility method to check if ad was loaded more than n hours ago.
     */
    private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
        long dateDifference = (new Date()).getTime() - this.loadTime;
        long numMilliSecondsPerHour = 3600000;
        return (dateDifference < (numMilliSecondsPerHour * numHours));
    }


    /**
     * Creates and returns ad request.
     */
    private AdRequest getAdRequest() {
        return new AdRequest.Builder().build();
    }

    /**
     * Utility method that checks if ad exists and can be shown.
     */
    public boolean isAdAvailable() {
        return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {

    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {
        currentActivity = activity;
    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        currentActivity = activity;
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        currentActivity = null;
    }
}

This is MyApplication for For Open Ads

public class MyApplication extends Application {

    private static AppOpenManager appOpenManager;


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

        appOpenManager = new AppOpenManager(this);
    }
}

This is the MainActivity.java class

//BANNER TST ID = ca-app-pub-3940256099942544/6300978111
    private static final String BANNER_AD_UNIT_ID = "ca-app-pub-3940256099942544/6300978111";
    private FrameLayout adContainerView;
    private AdView adView;
    AdsManager adsManager;

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

        



        // Initializing Mobile SDK for both Admob Banner and Interstitial
        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        //Interstitial Ads Called from AdsManager
        adsManager = new AdsManager(this);
        final InterstitialAd mInterstitialAd = adsManager.createInterstitialAds();


        // For Banner Ads
        adContainerView = findViewById(R.id.ad_view_container);
        // Step 1 - Create an AdView and set the ad unit ID on it.
        adView = new AdView(this);
        adView.setAdUnitId(BANNER_AD_UNIT_ID);
        adContainerView.addView(adView);
        loadBanner();




        Button CardButton = (Button)findViewById(R.id.card);
        CardButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    Intent cardIntent = new Intent(MainActivity.this, NewActivity0.class);
                    startActivity(cardIntent);

            }
        });
        

    }



    // FOR BANNER AND INTERSTITIAL ADS
    /** 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();
            adsManager.createInterstitialAds();
        }
    }
    /** Called before the activity is destroyed */
    @Override
    public void onDestroy() {
        if (adView != null) {
            adView.destroy();
        }
        super.onDestroy();
    }
    private void loadBanner() {
        // Create an ad request. Check your logcat output for the hashed device ID to
        // get test ads on a physical device. e.g.
        // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
        adView = new AdView(this);
        adView.setAdUnitId(BANNER_AD_UNIT_ID);
        adContainerView.removeAllViews();
        adContainerView.addView(adView);

        AdSize adSize = getAdSize();
        adView.setAdSize(adSize);

        AdRequest adRequest =
                new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();

        // Start loading the ad in the background.
        adView.loadAd(adRequest);
    }
    private AdSize getAdSize() {
        // Determine the screen width (less decorations) to use for the ad width.
        Display display = getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);

        float density = outMetrics.density;

        float adWidthPixels = adContainerView.getWidth();

        // If the ad hasn't been laid out, default to the full screen width.
        if (adWidthPixels == 0) {
            adWidthPixels = outMetrics.widthPixels;
        }

        int adWidth = (int) (adWidthPixels / density);

        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth);
    }


}


This is **NewActivity0.java** class where i showed Interstial Ads

//BANNER TST ID = ca-app-pub-3940256099942544/6300978111
    private static final String BANNER_AD_UNIT_ID = "ca-app-pub-3940256099942544/6300978111";
    private FrameLayout adContainerView;
    private AdView adView;


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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
 

        // Initialize the Mobile Ads SDK.
        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {}
        });
        adContainerView = findViewById(R.id.ad_view_container);
        // Since we're loading the banner based on the adContainerView size, we need to wait until this
        // view is laid out before we can get the width.
        adContainerView.post(new Runnable() {
            @Override
            public void run() {
                loadBanner();
            }
        });

        AdsManager adsManager = new AdsManager(this);
        InterstitialAd mInterstitialAd = adsManager.getInterstitialAd();
        if (mInterstitialAd != null) {
            mInterstitialAd.show(this);
        } else {
            Log.d("---Admob", "The interstitial ad wasn't ready yet.");
            // Intent intent = new Intent(MainActivity.this, MainActivity2.class);
            // startActivity(intent);
        }

    }


    /** 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() {
        // Create an ad request. Check your logcat output for the hashed device ID to
        // get test ads on a physical device. e.g.
        // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
        adView = new AdView(this);
        adView.setAdUnitId(BANNER_AD_UNIT_ID);
        adContainerView.removeAllViews();
        adContainerView.addView(adView);

        AdSize adSize = getAdSize();
        adView.setAdSize(adSize);

        AdRequest adRequest =
                new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();

        // Start loading the ad in the background.
        adView.loadAd(adRequest);
    }
    private AdSize getAdSize() {
        // Determine the screen width (less decorations) to use for the ad width.
        Display display = getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);

        float density = outMetrics.density;

        float adWidthPixels = adContainerView.getWidth();

        // If the ad hasn't been laid out, default to the full screen width.
        if (adWidthPixels == 0) {
            adWidthPixels = outMetrics.widthPixels;
        }

        int adWidth = (int) (adWidthPixels / density);

        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth);
    }
}

This is the LOGCAT where the warning is shown

2021-03-03 07:49:30.412 15190-16442/com.joseph.card I/System.out: [OkHttp] sendRequest>>
2021-03-03 07:49:30.418 15190-16442/com.joseph.card I/System.out: [OkHttp] sendRequest<<
2021-03-03 07:49:30.828 15190-15755/com.joseph.card W/OkHttpClient: A connection to https://googleads.g.doubleclick.net/ was leaked. Did you forget to close a response body?
2021-03-03 07:49:30.830 15190-15527/com.joseph.card D/Surface: Surface::disconnect(this=0x6e7d8800,api=1)
2021-03-03 07:49:31.076 15190-15190/com.joseph.card V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = ViewRoot{913b0d4 com.joseph.card/com.joseph.card.MainActivity,ident = 12}, this = [email protected][MainActivity]
2021-03-03 07:49:31.516 15190-15190/com.joseph.card I/DynamiteModule: Considering local module com.google.android.gms.ads.dynamite:0 and remote module com.google.android.gms.ads.dynamite:204890103
2021-03-03 07:49:31.516 15190-15190/com.joseph.card I/DynamiteModule: Selected remote version of com.google.android.gms.ads.dynamite, version >= 204890103
2021-03-03 07:49:31.861 15190-16441/com.joseph.card I/System.out: [OkHttp] sendRequest>>
2021-03-03 07:49:31.869 15190-16441/com.joseph.card I/System.out: [OkHttp] sendRequest<<
2021-03-03 07:49:31.996 15190-15205/com.joseph.card I/zygote: Background concurrent copying GC freed 115671(6MB) AllocSpace objects, 55(2MB) LOS objects, 60% free, 5MB/14MB, paused 419us total 183.571ms
2021-03-03 07:49:32.267 15190-15190/com.joseph.card I/DynamiteModule: Considering local module com.google.android.gms.ads.dynamite:0 and remote module com.google.android.gms.ads.dynamite:204890103
2021-03-03 07:49:32.267 15190-15190/com.joseph.card I/DynamiteModule: Selected remote version of com.google.android.gms.ads.dynamite, version >= 204890103
2021-03-03 07:49:32.334 15190-15190/com.joseph.card W/Ads: #004 The webview is destroyed. Ignoring action.
2021-03-03 07:49:32.334 15190-15190/com.joseph.card I/chatty: uid=10647(com.joseph.card) identical 1 line
2021-03-03 07:49:32.335 15190-15190/com.joseph.card W/Ads: #004 The webview is destroyed. Ignoring action.
2021-03-03 07:49:32.367 15190-15190/com.joseph.card W/Ads: #004 The webview is destroyed. Ignoring action.
2021-03-03 07:49:32.480 15190-16471/com.joseph.card I/System.out: [OkHttp] sendRequest>>
2021-03-03 07:49:32.481 15190-16471/com.joseph.card I/System.out: [OkHttp] sendRequest<<
2021-03-03 07:50:15.991 15190-15347/com.joseph.card D/libc-netbsd: getaddrinfo: get result from proxy gai_error = 0
2021-03-03 07:50:17.004 15190-15190/com.joseph.card D/---Admob: The ad was dismissed.
2021-03-03 07:50:17.091 15190-15527/com.joseph.card E/libPowerStretch: LUCID Battery Level = 70% Battery Temp = -100 Cpu Temp = -100
2021-03-03 07:50:17.157 15190-15190/com.joseph.card W/Ads: #004 The webview is destroyed. Ignoring action.
2021-03-03 07:50:17.161 15190-15190/com.joseph.card I/chatty: uid=10647(com.joseph.card) identical 2 lines
2021-03-03 07:50:17.165 15190-15190/com.joseph.card W/Ads: #004 The webview is destroyed. Ignoring action.
2021-03-03 07:50:17.173 15190-15190/com.joseph.card W/Ads: #004 The webview is destroyed. Ignoring action.
2021-03-03 07:50:17.196 15190-15190/com.joseph.card V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{d7449e0 com.joseph.card/com.joseph.card.activity.CardActivity,ident = 16}, this = [email protected][CardActivity]
2021-03-03 07:50:17.317 15190-15527/com.joseph.card D/Surface: Surface::disconnect(this=0x6df6a800,api=1)
2021-03-03 07:50:17.527 15190-15190/com.joseph.card D/View: [Warning] assignParent to null: this = [email protected][AdActivity]
2021-03-03 07:50:17.541 15190-15190/com.joseph.card D/WindowClient: Remove from mViews: [email protected][AdActivity], this = [email protected]
2021-03-03 07:50:26.527 15190-15190/com.joseph.card D/DynamitePackage: Instantiating com.google.android.gms.ads.ChimeraAdManagerCreatorImpl
2021-03-03 07:50:26.555 15190-15190/com.joseph.card I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("2E4E5C3489EFBBFC5446FCA709869E91")) to get test ads on this device.
2021-03-03 07:50:26.655 15190-15190/com.joseph.card V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{913b0d4 com.joseph.card/com.joseph.card.MainActivity,ident = 12}, this = [email protected][MainActivity]

Source: Android Questions

LEAVE A COMMENT