替换@OnLifecycleEvent(ON_START)为@OnLifecycleEvent(Lifecycle.Event.ON_START)。
在onCreate()方法中初始化AppOpenAd,并在onStart()或onResume()方法中加载广告。以下是示例代码:
public class MainActivity extends AppCompatActivity implements LifecycleObserver {
private AppOpenAd appOpenAd;
private AppOpenAd.AppOpenAdLoadCallback loadCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化AppOpenAd
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
AdRequest adRequest = new AdRequest.Builder().build();
AppOpenAd.load(MainActivity.this, getString(R.string.admob_app_open_ad_id), adRequest, AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, new AppOpenAd.AppOpenAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull AppOpenAd ad) {
appOpenAd = ad;
if (loadCallback != null) {
loadCallback.onAdLoaded(ad);
}
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError error) {
Log.e("AppOpenAd", "onAdFailedToLoad: " + error.getMessage());
if (loadCallback != null) {
loadCallback.onAdFailedToLoad(error);
}
}
});
}
});
}
// 加载广告
private void loadAd() {
if (appOpenAd != null) {
appOpenAd.show(this);
} else {
loadCallback = new AppOpenAd.AppOpenAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull AppOpenAd ad) {
appOpenAd = ad;
if (loadCallback != null) {
loadCallback.onAdLoaded(ad);
}
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError error) {
Log.e("AppOpenAd", "onAdFailedToLoad: " + error.getMessage());
if (load