我想在我的游戏中添加插页式广告。我找到的示例代码工作正常,但问题是它在我的应用程序启动时出现一次。我想控制广告的外观,并在其他类中调用我的displayInterstitial()方法,比如从我的GameScreen类中调用。如何调用其他任何类别的广告?
import com.google.android.gms.ads.*;
public class BannerExample extends Activity {
private InterstitialAd interstitial;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create the interstitial.
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(MY_AD_UNIT_ID);
// Create ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
}
// Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
答案 0 :(得分:0)
您可以使用外观来实现此目的。确保从UI线程进行调用。以下应该有效:
定义一个接口,例如MyAdListener.java:
public interface MyAdListener{
public void displayInterstitial();
}
在游戏的主要活动中,实施界面:
public class BannerExample extends Activity implements MyAdListener{
private InterstitialAd interstitial;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create the interstitial.
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(MY_AD_UNIT_ID);
// Create ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
}
// Invoke displayInterstitial() when you are ready to display an interstitial.
@Override
public void displayInterstitial() {
runOnUiThread(new Runnable() {
@Override
public void run(){
if (interstitial.isLoaded()) interstitial.show();
}
});
}
Then finally in your game screen's class:
public class GameScreen extends View implements Runnable{
MyAdListener myAdListener;
public GameScreen(Context context){
myAdListener = (MyAdListener)context;
//display the interstitial ad
myAdListener.displayInterstitial();
}
}
如果您需要进一步的帮助,请告诉我