|
| 1 | +/* |
| 2 | + * Copyright 2024 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.google.android.gms.example.jetpackcomposedemo.formats |
| 18 | + |
| 19 | +import android.content.Context |
| 20 | +import android.util.Log |
| 21 | +import androidx.compose.foundation.background |
| 22 | +import androidx.compose.foundation.layout.Arrangement |
| 23 | +import androidx.compose.foundation.layout.Box |
| 24 | +import androidx.compose.foundation.layout.Column |
| 25 | +import androidx.compose.foundation.layout.fillMaxWidth |
| 26 | +import androidx.compose.foundation.layout.height |
| 27 | +import androidx.compose.foundation.layout.padding |
| 28 | +import androidx.compose.foundation.layout.width |
| 29 | +import androidx.compose.foundation.lazy.LazyColumn |
| 30 | +import androidx.compose.foundation.lazy.items |
| 31 | +import androidx.compose.material3.CircularProgressIndicator |
| 32 | +import androidx.compose.material3.MaterialTheme |
| 33 | +import androidx.compose.material3.Surface |
| 34 | +import androidx.compose.material3.Text |
| 35 | +import androidx.compose.runtime.Composable |
| 36 | +import androidx.compose.runtime.DisposableEffect |
| 37 | +import androidx.compose.runtime.LaunchedEffect |
| 38 | +import androidx.compose.runtime.getValue |
| 39 | +import androidx.compose.runtime.mutableStateOf |
| 40 | +import androidx.compose.runtime.remember |
| 41 | +import androidx.compose.runtime.setValue |
| 42 | +import androidx.compose.ui.Modifier |
| 43 | +import androidx.compose.ui.platform.LocalConfiguration |
| 44 | +import androidx.compose.ui.platform.LocalContext |
| 45 | +import androidx.compose.ui.platform.LocalInspectionMode |
| 46 | +import androidx.compose.ui.tooling.preview.Preview |
| 47 | +import androidx.compose.ui.unit.dp |
| 48 | +import com.example.jetpackcomposedemo.R |
| 49 | +import com.google.android.gms.ads.AdListener |
| 50 | +import com.google.android.gms.ads.AdRequest |
| 51 | +import com.google.android.gms.ads.AdSize |
| 52 | +import com.google.android.gms.ads.AdView |
| 53 | +import com.google.android.gms.ads.LoadAdError |
| 54 | +import com.google.android.gms.compose_util.BannerAd |
| 55 | +import com.google.android.gms.example.jetpackcomposedemo.GoogleMobileAdsApplication.Companion.BANNER_AD_UNIT_ID |
| 56 | +import com.google.android.gms.example.jetpackcomposedemo.GoogleMobileAdsApplication.Companion.TAG |
| 57 | +import com.google.android.gms.example.jetpackcomposedemo.ui.theme.JetpackComposeDemoTheme |
| 58 | +import kotlin.coroutines.resume |
| 59 | +import kotlinx.coroutines.async |
| 60 | +import kotlinx.coroutines.awaitAll |
| 61 | +import kotlinx.coroutines.supervisorScope |
| 62 | +import kotlinx.coroutines.suspendCancellableCoroutine |
| 63 | + |
| 64 | +@Composable |
| 65 | +fun LazyBannerScreen(modifier: Modifier = Modifier) { |
| 66 | + val context = LocalContext.current |
| 67 | + val isPreviewMode = LocalInspectionMode.current |
| 68 | + val deviceCurrentWidth = LocalConfiguration.current.screenWidthDp |
| 69 | + val adsToLoad = 5 |
| 70 | + |
| 71 | + // Indicate whether the banner ads are currently being loaded. |
| 72 | + var isLoadingAds by remember { mutableStateOf(true) } |
| 73 | + var loadedAds by remember { mutableStateOf<List<AdView>>(emptyList()) } |
| 74 | + val fillerText = loadFillerText(context) |
| 75 | + |
| 76 | + // Load ads when on launch of the composition. |
| 77 | + LaunchedEffect(Unit) { |
| 78 | + if (!isPreviewMode) { |
| 79 | + loadedAds = loadBannerAds(context, adsToLoad, deviceCurrentWidth) |
| 80 | + } |
| 81 | + isLoadingAds = false |
| 82 | + } |
| 83 | + |
| 84 | + // Display a loading indicator if ads are still being fetched. |
| 85 | + if (isLoadingAds) { |
| 86 | + CircularProgressIndicator(modifier = modifier.width(100.dp).height(100.dp)) |
| 87 | + } else { |
| 88 | + // Display a lazy list with loaded ads and filler content. |
| 89 | + LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) { |
| 90 | + items(loadedAds) { adView -> |
| 91 | + Column { |
| 92 | + BannerAd(adView, modifier.fillMaxWidth()) |
| 93 | + // Display the filler content. |
| 94 | + fillerText.forEach { content -> |
| 95 | + Box( |
| 96 | + modifier |
| 97 | + .fillMaxWidth() |
| 98 | + .background(MaterialTheme.colorScheme.primaryContainer) |
| 99 | + .padding(8.dp) |
| 100 | + ) { |
| 101 | + Text( |
| 102 | + text = content, |
| 103 | + modifier.padding(8.dp), |
| 104 | + style = MaterialTheme.typography.bodyMedium, |
| 105 | + ) |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + // Clean up the AdViews after use. |
| 114 | + DisposableEffect(Unit) { onDispose { loadedAds.forEach { adView -> adView.destroy() } } } |
| 115 | +} |
| 116 | + |
| 117 | +@Preview |
| 118 | +@Composable |
| 119 | +private fun LazyBannerScreenPreview() { |
| 120 | + JetpackComposeDemoTheme { |
| 121 | + Surface(color = MaterialTheme.colorScheme.background) { LazyBannerScreen() } |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +private suspend fun loadBannerAd(context: Context, width: Int): Result<AdView> { |
| 126 | + return suspendCancellableCoroutine { continuation -> |
| 127 | + val adView = AdView(context) |
| 128 | + adView.adUnitId = BANNER_AD_UNIT_ID |
| 129 | + val adSize = AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(context, width) |
| 130 | + adView.setAdSize(adSize) |
| 131 | + adView.adListener = |
| 132 | + object : AdListener() { |
| 133 | + override fun onAdLoaded() { |
| 134 | + Log.d(TAG, "Banner ad was loaded.") |
| 135 | + continuation.resume(Result.success(adView)) |
| 136 | + } |
| 137 | + |
| 138 | + override fun onAdFailedToLoad(error: LoadAdError) { |
| 139 | + Log.e(TAG, "Banner ad failed to load: ${error.message}") |
| 140 | + adView.destroy() |
| 141 | + continuation.resume(Result.failure(Error(error.message))) |
| 142 | + } |
| 143 | + |
| 144 | + override fun onAdImpression() { |
| 145 | + Log.d(TAG, "Banner ad recorded an impression.") |
| 146 | + } |
| 147 | + |
| 148 | + override fun onAdClicked() { |
| 149 | + Log.d(TAG, "Banner ad was clicked.") |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + continuation.invokeOnCancellation { |
| 154 | + // When the coroutine is cancelled, clean up resources. |
| 155 | + adView.destroy() |
| 156 | + } |
| 157 | + |
| 158 | + val adRequest = AdRequest.Builder().build() |
| 159 | + adView.loadAd(adRequest) |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +private suspend fun loadBannerAds(context: Context, count: Int, width: Int): List<AdView> = |
| 164 | + supervisorScope { |
| 165 | + List(count) { |
| 166 | + async { |
| 167 | + try { |
| 168 | + loadBannerAd(context, width).getOrNull() |
| 169 | + } catch (e: Error) { |
| 170 | + null |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + .awaitAll() |
| 175 | + .filterNotNull() |
| 176 | + } |
| 177 | + |
| 178 | +fun loadFillerText(context: Context): List<String> { |
| 179 | + val fillerContent = context.resources.getStringArray(R.array.lazy_banner_filler_content) |
| 180 | + return fillerContent.toList() |
| 181 | +} |
0 commit comments