Google received feedback via Play Console crash reports about Application Not Responding (ANRs) errors related to the Google Mobile Ads SDK. After analyzing these reports, Google updated the SDK implementation best practices to reduce ANR rates. The recommended best practices are:
Initialize the Mobile Ads SDK on a Background Thread
Previously, the best practice was to specify the OPTIMIZE_INITIALIZATION
manifest flag. However, some work on the calling thread was still required. Now, we recommend calling MobileAds.initialize()
on a background thread to handle this work asynchronously. Google provided the Kotlin example below:
import com.google.android.gms.ads.MobileAds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CoroutineScope(Dispatchers.IO).launch {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this@MainActivity) {}
runOnUiThread {
// Load an ad on the main thread.
loadAd()
}
}
}
}
Note: When calling MobileAds.initialize()
on a background thread, the OPTIMIZE_INITIALIZATION
manifest flag is no longer required.
Enable Optimization Flag for Ad Loading
By enabling the OPTIMIZE_AD_LOADING
manifest flag, most ad loading tasks can be offloaded to a background thread, reducing the occurrence of ANRs. This flag should be enabled in your app's AndroidManifest.xml
file. Google shared the example below:
<manifest>
...
<application>
...
<meta-data
android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING"
android:value="true"/>
</application>
</manifest>
Google have updated all of the Android example apps to implement these best practices. For more details check out the source below.