Hello I am trying to integrated Banner Ad using RevMob in Libgdx. But it is not displaying for some reason.
I am using the following code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_game_new);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
// cfg.useGL20 = false;
final RelativeLayout gameLayout = new RelativeLayout(this);
RevMobIntegration revmob = new RevMobIntegration(this);
RelativeLayout bannerLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_VERTICAL);
bannerLayout.setLayoutParams(adParams);
game = new MyGdxGame(GameActivity.this, revmob);
game.setRedirectionListener(this);
View gameView = initializeForView(game, cfg);
requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Add the libgdx view
gameLayout.addView(gameView);
// gameLayout.addView(bannerLayout);
Log.d("RevMob", "Checking BannerAd");
if (revmob.getBannerAd() != null) {
Log.d("RevMob", "Displaying Called");
gameLayout.addView(revmob.getBannerAd());
}
// Hook it all up
setContentView(gameLayout);
this.onPause();
this.onResume();
gameLayout.refreshDrawableState();
initChartboost();
// startRevMobSession();
}
Here is the RevMobIntegration class :
public class RevMobIntegration implements RevmobAdInterface {
private static final String APPLICATION_ID = "YourAdmobAppIDHere";
// Set this to false when creating the version for the store.
private static final boolean DEBUG = true;
private RevMobAdsListener listener;
private RevMobFullscreen fullscreenAd;
private RevMobBanner bannerAd;
private Activity application;
private RevMob revmob;
public RevMobIntegration(Activity _application) {
this.application = _application;
startRevMobSession();
}
public void startRevMobSession() {
//RevMob's Start Session method:
revmob = RevMob.startWithListener(application, new RevMobAdsListener() {
#Override
public void onRevMobSessionStarted() {
loadBanner(); // Cache the banner once the session is started
Log.i("RevMob", "Session Started");
}
#Override
public void onRevMobSessionNotStarted(String message) {
//If the session Fails to start, no ads can be displayed.
Log.i("RevMob", "Session Failed to Start");
}
}, application.getString(R.string.rev_mob_app_id));
}
//RevMob
public void loadBanner() {
bannerAd = revmob.preLoadBanner(application, new RevMobAdsListener() {
#Override
public void onRevMobAdReceived() {
showBannerAd(true);
Log.i("RevMob", "Banner Ready to be Displayed"); //At this point,
the banner is ready to be displayed.
}
#Override
public void onRevMobAdNotReceived(String message) {
Log.i("RevMob", "Banner Not Failed to Load");
}
#Override
public void onRevMobAdDisplayed() {
Log.i("RevMob", "Banner Displayed");
}
});
}
#Override
public void showBannerAd(boolean show) {
if(show) {
Log.i("RevMob", "Showing");
if(bannerAd == null) {
startRevMobSession();
} else {
Log.i("RevMob", "Banner Displayed");
bannerAd.show();
}
} else {
bannerAd.hide();
}
}
public RevMobBanner getBannerAd() { return bannerAd; }
}
I have integrated the RevMob in my Activities and it is working fine. But for the Game Screen the ad is initializing but not displaying.
Any suggestions?
It seems revmob.getBannerAd() return null because bannerAd object created when loadBanner(); called. RevMob take some time to start it's session.
if (revmob.getBannerAd() != null) {
Log.d("RevMob", "Displaying Called");
gameLayout.addView(revmob.getBannerAd());
}
You can check this repo for clarification also you can take a look of this class.
Related
I successfully implemented banner ad in my libgdx game, now i am trying to implementing interstitial ad. I want to show ad on the button click but the ad is not showing on the screen, i am using log to know if the ad is loading and it is loading everytime but not visible on the screen. i am using multiple screen classes in the game. I have watched several tutorials on it but nothing seems to work.
public class AndroidLauncher extends AndroidApplication implements AdService{
private InterstitialAd interstitialAd;
private ScheduledExecutorService scheduler;
private static final String BANNER_ID = "ca-app-pub-3940256099942544/6300978111";
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
//create a gameView and a bannerAd AdView
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new BabyGame(this), config);
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(BANNER_ID); // Put in your secret key here
AdRequest adRequest = new AdRequest.Builder().addTestDevice("6D0D171A0065AD4E19656B813BC8F493").build();
adView.loadAd(adRequest);
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {}
#Override
public void onAdClosed() {
loadIntersitialAd();
}
});
loadIntersitialAd();
}
private void loadIntersitialAd(){
AdRequest interstitialRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialRequest);
}
#Override
public void showInterstitial() {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded())
interstitialAd.show();
else
loadIntersitialAd();
}
});
}
#Override
public boolean isInterstitialLoaded() {
return interstitialAd.isLoaded();
}
}
This is the BabyGame.java
public class BabyGame extends Game
{
public AdService adService;
BabyGame(AdService ads){
adService = ads;
}
public void create()
{
BabyOrange bp = new BabyOrange(this);
setScreen( bp );
}
}
here is the interface
public interface AdService {
boolean isInterstitialLoaded();
void showInterstitial();
}
I want to show ads here in the BabyOrange.java when the button touched.
public class BabyOrange extends BabyScreen {
private BabyActor bg;
private BabyActor phone;
private ImageButton buttonLeft,buttonRight;
public AdService adService;
private Table table;
private AssetManager asset;
private TextureAtlas atlas;
public BabyOrange(Game g){
super(g);
}
#Override
public void create() {
asset = new AssetManager();
asset.load("background-orange.png",Texture.class);
asset.load("orange-ph.png",Texture.class);
asset.finishLoading();
bg = new BabyActor();
bg.setTexture(asset.get("background-orange.png",Texture.class));
bg.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
ph = new BabyActor();
ph.setTexture(asset.get("orange-ph.png",Texture.class));
ph.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
TextureRegion btLeft = new TextureRegion(new Texture("NUMBEROFF.png"));
Drawable drawableLeft = new TextureRegionDrawable(new TextureRegion(btLeft));
buttonLeft = new ImageButton(drawableLeft);
TextureRegion btRight = new TextureRegion(new Texture("VEHICLEOFF.png"));
Drawable drawableRight = new TextureRegionDrawable(new TextureRegion(btRight));
buttonRight = new ImageButton(drawableRight);
stage.addActor(bg);
stage.addActor(phone);
Gdx.input.setInputProcessor(stage);
buttonRight.addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
game.setScreen(new BabyGreen(game));
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
adService.showInterstitial();
}
});
return true;
}
});
buttonLeft.addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
game.setScreen(new BabyBlue(game));
return true;
}
});
table = new Table();
table.padLeft(40);
table.setPosition(phone.getWidth()/2,phone.getHeight()/2*0.6f);
table.row().size(stage1.getWidth()/100*20,stage1.getWidth()/100*20);
table.add(buttonLeft);
table.add(buttonCenter);
table.add(buttonRight);
stage.addActor(table);
}
public void dispose(){
bg.getRegion().getTexture().dispose();
phone.getRegion().getTexture().dispose();
stage.dispose();
stage1.dispose();
}
}
Anybody know how to show the interstitial ads when the user click the button second time.I mean when the user click the button once then the ad should not appear but whenever the user click the same button second time then the ad must show..
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ShowInterstitial showInterstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showInterstitial = new ShowInterstitial(this);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.app_bar);
/*toolbar = findViewById(R.id.app_bar);
toolbar.setTitle("hell");
toolbar.*/
}
int counter = 0;
public void onClick(View view) {
if(view.getId() == R.id.ll1 ) {
counter++;
if (counter == 2) {
counter = 0;
Intent intent = new Intent(this, AggregatesActivity.class);
startActivity(intent);
if (showInterstitial != null && ShowInterstitial.isLoaded())
showInterstitial.showInterstitial();
}
}
and ShowInterstitial code is here which i calling in different activities.
public class ShowInterstitial {
private InterstitialAd mInterstitialAd;
private Context context;
private boolean isAddReplace = false;
public ShowInterstitial(Context context) {
this.context = context;
mInterstitialAd = newInterstitialAd(context);
loadInterstitial();
}
private InterstitialAd newInterstitialAd(final Context context) {
InterstitialAd interstitialAd = new InterstitialAd(context);
/*if (!isAddReplace)
interstitialAd.setAdUnitId(context.getString(R.string.interstitial_one));*/
interstitialAd.setAdUnitId(context.getString(R.string.interstitial_one));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
isAddReplace = !isAddReplace;
}
#Override
public void onAdFailedToLoad(int errorCode) {
}
#Override
public void onAdClosed() {
goToNextLevel();
}
});
return interstitialAd;
}
public boolean showInterstitial() {
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
goToNextLevel();
}
return false;
}
public void loadInterstitial() {
// Disable the next level button and load the ad.
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
private void goToNextLevel() {
// Show the next level and reload the ad to prepare for the level after.
mInterstitialAd = newInterstitialAd(context);
loadInterstitial();
}
}
#Sufyan Hashmi you need a int variable whose value will increase on every click whenever the value is 2 you should call load inerestitial ad and assign the variable's value zero.
int counter = 0;
if(view.getId()==R.id.ll1)
{
counter++;
if (counter == 2) {
counter = 0;
Intent intent = new Intent(this, AggregatesActivity.class);
startActivity(intent);
if (showInterstitial != null && showInterstitial.isLoaded())
showInterstitial.showInterstitial();
}
}
How to show the interstitial ads on second click in android?
You can take boolean variable and manage click event based on that boolean variable
Example : take a boolean variable with true value
Than inside ClickListener when user clicks the button check that boolean variable is true means use clicked first time the button
and change the value of boolean variable to false
SAMPLE CODE
take one boolean variable
boolean isFirstTimeClick=true;
Now make your ClickListener like this
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isFirstTimeClick){
isFirstTimeClick=false;
Toast.makeText(PicturePreviewActivity.this, "First Time Click", Toast.LENGTH_SHORT).show();
}else {
isFirstTimeClick=true;
Toast.makeText(PicturePreviewActivity.this, "Second Time Click", Toast.LENGTH_SHORT).show();
}
}
});
Made a game with Libgdx and eventually got GPGS Leaderboard and Achievements to work. Or so I thought.
They run fine on my phone and tablet when I install the APK directly through Android Studio but it won't allow users to sign in when they have downloaded the game from Google Play Store.
Failed to sign in. Please check your network connection and try again
The SHA-1 matches in console.developers.google.com/apis/credentials/oauthclient/ and gradle.
Leaderboards etc have all been published days ago.
What have I forgotten to do? Is there a new SHA-1 I should add to developer console that I don't know how to find? I'm "certain" I've covered all the basics illustrated in other questions on SO.
I am thinking/hoping it is something in the developer console I've forgotten/missed.
Here's AndroidLauncher though just in case I'm wrong about that, thanks in advance:
package com.weavernap.chuggydodge;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.view.View;
import android.widget.RelativeLayout;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;
import com.weavernap.cdHelpers.AdsController;
public class AndroidLauncher extends AndroidApplication implements GameHelper.GameHelperListener, AdsController {
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
private static final String BANNER_AD_UNIT_ID = "ca-app-pub-3737397260010456/7958274520";
private static final String INTERSTITIAL_AD_UNIT_ID = "ca-app-pub-3737397260010456/3314422124";
protected AdView adView;
private InterstitialAd interstitialAd;
protected View gameView;
private GameHelper gameHelper;
// private AdsController adsController;
// private GoogleApiClient mGoogleApiClient;
private SharedPreferences prefs;
private boolean writeLogs = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-3737397260010456~9090257326");
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
RelativeLayout relativeLayout = new RelativeLayout(this);
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(-1, -1));
AdView adView = this.createAdView();
relativeLayout.addView(adView);
relativeLayout.addView(this.createGameView(config));
this.setContentView(relativeLayout);
this.startAdvertising(adView);
this.interstitialAd = new InterstitialAd(this);
this.interstitialAd.setAdUnitId(INTERSTITIAL_AD_UNIT_ID);
if (this.gameHelper == null) {
this.gameHelper = new GameHelper(this, 1);
this.gameHelper.enableDebugLog(this.writeLogs);
}
this.gameHelper.setup(this);
//
// // Create a gameView and a bannerAd AdView
// View gameView = initializeForView(new CDGame(this), config);
// setupAds();
// // Define the layout
// RelativeLayout layout = new RelativeLayout(this);
// layout.addView(gameView, ViewGroup.LayoutParams.MATCH_PARENT,
// ViewGroup.LayoutParams.MATCH_PARENT);
// RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
// ViewGroup.LayoutParams.MATCH_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT);
// params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
// layout.addView(bannerAd, params);
//
// setContentView(layout);
}
#Override
public void onStart() {
super.onStart();
gameHelper.onStart(this);
}
#Override
public void onStop() {
super.onStop();
gameHelper.onStop();
}
#Override
public void onActivityResult(int request, int response, Intent data) {
super.onActivityResult(request, response, data);
gameHelper.onActivityResult(request, response, data);
}
#Override
public void showOrLoadInterstitial(final boolean showAd) {
try {
this.runOnUiThread(new Runnable() {
public void run() {
if (AndroidLauncher.this.interstitialAd.isLoaded() && showAd) {
AndroidLauncher.this.interstitialAd.show();
return;
} //else
{
AdRequest adRequest = new AdRequest.Builder().build();
AndroidLauncher.this.interstitialAd.loadAd(adRequest);
}
}
});
return;
} catch (Exception e) {
Gdx.app.log("ChuggerDodge.ERROR", "Exception in showOrLoadInterstitial:" + e.toString());
return;
}
}
#Override
public void submitScoreGPGS(int score) {
if (this.getSignedInGPGS()) {
Games.Leaderboards.submitScore(this.gameHelper.getApiClient(), this.getString(R.string.leaderboard_top_scores), score);
}
}
#Override
public void unlockAchievementGPGS(int score) {
if (this.getSignedInGPGS()) {
if (score == 0) {
Games.Achievements.unlock(this.gameHelper.getApiClient(),
this.getString(R.string.achievement_the_every_loser_wins_trophy));
}
if (score > 3) {
Games.Achievements.unlock(this.gameHelper.getApiClient(),
this.getString(R.string.achievement_not_completely_useless));
}
if (score > 19) {
Games.Achievements.unlock(this.gameHelper.getApiClient(),
this.getString(R.string.achievement_hey_youre_all_right_you_are_));
}
if (score == 42) {
Games.Achievements.unlock(this.gameHelper.getApiClient(),
this.getString(R.string.achievement_the_hyperintelligent_pandimensional_being_prize));
}
if (score > 43) {
Games.Achievements.unlock(this.gameHelper.getApiClient(),
this.getString(R.string.achievement_wowzers__youre_about_as_good_as_me_now_));
}
if (score > 76) {
Games.Achievements.unlock(this.gameHelper.getApiClient(),
this.getString(R.string.achievement_actually_thats_quite_impressive_));
}
}
}
#Override
public void getGPGSLeaderboard() {
if (this.gameHelper.isSignedIn()) {
this.startActivityForResult(Games.Leaderboards.getLeaderboardIntent(this.gameHelper.getApiClient(), this.getString(R.string.leaderboard_top_scores)), 100);
return;
} else {
if (this.gameHelper.isConnecting()) return;
{
this.loginGPGS();
return;
}
}
}
#Override
public boolean getSignedInGPGS() {
if (this.gameHelper != null) {
System.out.println("Superduperdavid");
return this.gameHelper.isSignedIn();
}
System.out.println("Nah");
return false;
}
//
#Override
public void loginGPGS() {
// if (!gameHelper.isSignedIn()) {
try {
runOnUiThread(new Runnable() {
public void run() {
gameHelper.beginUserInitiatedSignIn();
}
});
return;
} catch (final Exception ex) {
Gdx.app.log("MainActivity", "Log in failed: " + ex.getMessage() + ".");
return;
}
//
}
//
#Override
public void getAchievementsGPGS() {
// if (gameHelper.isSignedIn()) {
startActivityForResult(Games.Achievements.getAchievementsIntent(gameHelper.getApiClient()), 101);
// } else if (!gameHelper.isConnecting()) {
// loginGPGS();
// }
}
//Following from toaster code
private AdView createAdView() {
this.adView = new AdView(this);
this.adView.setAdSize(AdSize.SMART_BANNER);
this.adView.setAdUnitId(BANNER_AD_UNIT_ID);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-1, -2);
layoutParams.addRule(12, -1);
layoutParams.addRule(14, -1);
this.adView.setLayoutParams(layoutParams);
this.adView.setBackgroundColor(Color.TRANSPARENT);
return this.adView;
}
private View createGameView(AndroidApplicationConfiguration androidApplicationConfiguration) {
this.gameView = this.initializeForView(new CDGame(this), androidApplicationConfiguration);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-1, -2);
layoutParams.addRule(10, -1);
layoutParams.addRule(14, -1);
layoutParams.addRule(2, this.adView.getId());
this.gameView.setLayoutParams(layoutParams);
return this.gameView;
}
private void startAdvertising(AdView adView) {
adView.loadAd(new AdRequest.Builder().build());
}
#Override
public void onDestroy() {
if (this.adView != null) {
this.adView.destroy();
}
super.onDestroy();
}
#Override
public void onPause() {
if (this.adView != null) {
this.adView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (this.adView != null) {
this.adView.resume();
}
}
#Override
public void onSignInFailed() {
gameHelper.getSignInError();
}
#Override
public void onSignInSucceeded() {
}
}
Okay, so at some point I had entered the debug SHA-1 into the developer console to get GPGS working during testing. But did not realise that you had to revert back to the original.
So following this and making the changes in the console did the trick pretty much straight away.
I have been following this tutorial: https://github.com/libgdx/libgdx/wiki/Admob-in-libgdx
I'm sure i have implemented everything correctly and am still getting a null pointer for the handler. Is there something wrong with the code in the tutorial?
Here is my Android Launcher Code:
public class AndroidLauncher extends AndroidApplication implements IActivityRequestHandler{
protected AdView adView;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
protected Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SHOW_ADS:
{
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS:
{
adView.setVisibility(View.GONE);
break;
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new PBGame(this));
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdUnitId("Secret Key");
adView.setAdSize(AdSize.BANNER);
adView.loadAd(new AdRequest.Builder()
.addTestDevice("Test Device")
.build());
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}
#Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
My Game Class:
public static final int VIRTUAL_WIDTH = 800;
public static final int VIRTUAL_HEIGHT = 480;
public static final float ASPECT_RATIO =
(float)VIRTUAL_WIDTH/(float)VIRTUAL_HEIGHT;
public static final int zeroMakerX = 400, zeroMakerY = 240;
public static Camera camera;
public static Rectangle viewport;
private IActivityRequestHandler myRequestHandler;
public PBGame(IActivityRequestHandler handler) {
myRequestHandler = handler;
}
#Override
public void create() {
AssetHandler.load();
super.setScreen(new TitleScreen(this));
AssetHandler.music.play();
AssetHandler.music.setLooping(true);
}
#Override
public void dispose() {
super.dispose();
}
}
Finally the ReqestHandler:
public interface IActivityRequestHandler {
public void showAds(boolean show);
}
The problem is as follows:
Your AdView object is defined locally inside the onCreate() function of the AndroidLauncher class. You then attempt to access it outside of onCreate() in the Handler object. The AdView object is out of scope. You should declare the AdView in your AndroidLauncher class outside of onCreate():
AdView adView;
Then in onCreate() you can instantiate it as you did:
// Create and setup the AdMob view
adView = new AdView(this);
adView.setAdUnitId("Secret Key");
adView.setAdSize(AdSize.BANNER);
adView.loadAd(new AdRequest.Builder()
.addTestDevice("Test Device")
.build());
the issue is: the ad doesn't show on first request, but when it makes the second request, it shows right. About 2 seconds before it make the second request, the ad of the first request shows up. Any ideas?
Thanks,
EDIT: I changed the gravity to TOP, and now it shows on the first time, but is showing just the top half of the ad, bizarre, any ideas?
#Override
protected void onSetContentView() {
if(adView != null){
return;
}
final FrameLayout frameLayout = new FrameLayout(this);
final FrameLayout.LayoutParams frameLayoutLayoutParams =
new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
final FrameLayout.LayoutParams adViewLayoutParams =
new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(getResources().getString(R.string.ad_unit_id));
adView.setAdListener(new ToastAdListener(this));
adView.loadAd(new AdRequest.Builder().build());
this.mRenderSurfaceView = new RenderSurfaceView(this);
mRenderSurfaceView.setRenderer(mEngine,this);
final android.widget.FrameLayout.LayoutParams surfaceViewLayoutParams =
new FrameLayout.LayoutParams(super.createSurfaceViewLayoutParams());
frameLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);
frameLayout.addView(adView, adViewLayoutParams);
this.setContentView(frameLayout, frameLayoutLayoutParams);
}
#Override
protected void onPause() {
if(adView!=null){
adView.pause();
}
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
if(adView!=null){
adView.resume();
}
}
#Override
protected void onDestroy() {
if(adView!=null){
adView.destroy();
}
super.onDestroy();
}
The problem was solved for me by adding the line
adView.setBackgroundColor(android.graphics.Color.TRANSPARENT);
The way I have done is as follows:
In the method which changes the visibility, I first check is the ad was loaded. If it was not, I don't change the visibility
Set an AdListener for the AdView. in the onReceivedAd(), I check the condition to hide it - if it should be hidden, I hide.
Works fine this way.
I have got the same problem, I solved this way:
Advertisement class:
public class Advertisement {
private AdView adView;
private final Handler adsHandler = new Handler();
public Advertisement(final Activity activity) {
adView = (AdView)activity.findViewById(R.id.adView);
}
//show the ads.
private void showAds () {
adView.loadAd(new AdRequest.Builder().build());
adView.setVisibility(android.view.View.VISIBLE);
adView.setEnabled(true);
}
//hide ads.
private void unshowAds () {
adView.loadAd(new AdRequest.Builder().build());
adView.setVisibility(android.view.View.INVISIBLE);
adView.setEnabled(false);
}
final Runnable unshowAdsRunnable = new Runnable() {
public void run() {
unshowAds();
}
};
final Runnable showAdsRunnable = new Runnable() {
public void run() {
showAds();
}
};
public void showAdvertisement() {
adsHandler.post(showAdsRunnable);
}
public void hideAdvertisement() {
adsHandler.post(unshowAdsRunnable);
}
}
In code:
...
public static Advertisement advertisement = new Advertisement(this);
...
public static void showAd()
{
if (advertisement != null)
advertisement.showAdvertisement();
}
public static void hideAd()
{
if (gangsterAdvertisement != null)
advertisement.hideAdvertisement();
}