2014-05-14 77 views
0

我完成了我的第一個應用程序,我想嘗試添加一些廣告。 我嘗試了由谷歌提供的教程,他們工作正常。 現在,當我嘗試在我的應用程序中實現添加時,我收到錯誤消息: 「IllegalStateException:必須在主UI線程上調用isLoaded」。Android中的插頁式廣告

因此,這裏是我在我的主要活動做了我的的onCreate方法:

public void onCreate(){ 
    // Create the interstitial. 
    interstitial = new InterstitialAd(this); 
    interstitial.setAdUnitId(MY_AD_UNIT_ID); 

    // Create ad request. 
    AdRequest adRequest = new AdRequest.Builder() 
    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) 
    .addTestDevice("xxxxxxxxxxxxxx") 
    .build(); 

    // Begin loading your interstitial. 
    interstitial.loadAd(adRequest); 
} 

在同一個活動,我有:

public void showInterstitial() { 
    if (interstitial.isLoaded()) { 
     interstitial.show(); 
     } 
    } 

所以,當我試圖調用showInterstitial方法我收到上述錯誤。 我現在坐了幾個小時,並找不到任何解決方案。

回答

0

我認爲下面的代碼將有助於解決您的問題。使用這個在你的上創建功能

interstitial.setAdListener(new AdListener() { 
    public void onAdLoaded() { 
     showInterstitial(); 
    } 
});  

否則你可以使用下面的代碼&你可以在一個設備進行測試。

protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 

interstitial = new InterstitialAd(this); 
interstitial.setAdUnitId("***********"); 

AdRequest adRequest = new AdRequest.Builder().build(); 
interstitial.loadAd(adRequest); 
interstitial.setAdListener(new AdListener() { 
public void onAdLoaded() { 
    displayInterstitial(); 
} 
}); 
} 

public void displayInterstitial() { 
if (interstitial.isLoaded()) { 
interstitial.show(); 
} 
}