I was able to put together the code from Libgdx and Google play to add Ads from adMob but I cannot seem to bring the banner on top of the game screen and the banner only shows once I hit the back bottom and exit the app.
My code is below
any help would be appreciated
Android main class
public class MainActivity extends AndroidApplication {
static AdView adView;
private static final String AD_UNIT_ID = "my id";
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
//cfg.useGL20 = false;
//initialize(new GameActivity(), false);
// 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);
View gameView = initializeForView(new GameActivity(), true);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("my device")
.build();
adView = new AdView(this);
adView.setAdSize(AdSize.FULL_BANNER);
adView.setAdUnitId(AD_UNIT_ID);
adView.loadAd(adRequest);
RelativeLayout.LayoutParams gameParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
gameParams.bottomMargin = 1;
layout.addView(gameView, gameParams);
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
layout.addView(adView, adParams);
setContentView(layout);
}
#Override
protected void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
#Override
protected void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
#Override
protected void onResume() {
if (adView != null) {
adView.resume();
}
super.onResume();
}
}
Solved see Edited code, added LayoutParams to the game view
I found it:
I just had to change
adView.setAdSize(AdSize.FULL_BANNER);
to
adView.setAdSize(AdSize.BANNER);
Related
I am struggling to implement an admob banner into my app because the setContentView() method is used for the surfaceView called gameView so creating the adView in xml cannot be applied to this framework as setContentView is already being used. And I don't know how to do this programmatically. Does anyone have a solution to this?
My main Activity:
public class GameMainActivity extends BaseGameActivity {
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
prefs = getPreferences(Activity.MODE_PRIVATE); // New line!
highScore = retrieveHighScore();
highScoreUnits = retrieveHighScoreUnits();
highScoreTens = retrieveHighScoreTens();
highScoreHundreds = retrieveHighScoreHundreds();
muteButton = retrieveMuteButton();
assets = getAssets();
sGame = new GameView(this, GAME_WIDTH, GAME_HEIGHT);
setContentView(sGame);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
and my custom surfaceView code
public class GameView extends SurfaceView implements Runnable {
private Bitmap gameImage;
private Rect gameImageSrc;
private Rect gameImageDst;
private Canvas gameCanvas;
private Painter graphics;
private Thread gameThread;
private volatile boolean running = false;
private volatile State currentState;
private InputHandler inputHandler;
public GameView(Context context, int gameWidth, int gameHeight) {
super(context);
gameImage = Bitmap.createBitmap(gameWidth, gameHeight,
Bitmap.Config.RGB_565);
gameImageSrc = new Rect(0, 0, gameImage.getWidth(),
gameImage.getHeight());
gameImageDst = new Rect();
gameCanvas = new Canvas(gameImage);
graphics = new Painter(gameCanvas);
SurfaceHolder holder = getHolder();
holder.addCallback(new Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
initInput();
if (currentState == null) {
setCurrentState(new LoadState());
}
initGame();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
pauseGame();
}
});
}
Use a RelativeLayout or a FrameLayout as your parent layout, then just define the layout parameters for the adView to be positioned (for example at the bottom center of the screen like this):
public class GameMainActivity extends BaseGameActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
prefs = getPreferences(Activity.MODE_PRIVATE); // New line!
highScore = retrieveHighScore();
highScoreUnits = retrieveHighScoreUnits();
highScoreTens = retrieveHighScoreTens();
highScoreHundreds = retrieveHighScoreHundreds();
muteButton = retrieveMuteButton();
assets = getAssets();
// Create an ad.
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// set background color of adview to force it to show
adView.setBackgroundColor(Color.TRANSPARENT);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
// Create an ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
// Request full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Create and set your game's view
sGame = new GameView(this, GAME_WIDTH, GAME_HEIGHT);
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(sGame);
layout.addView(adView, adParams);
setContentView(layout);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
I'm trying to set adUnitId programmatically to ads from the new Google Play services (old AdMob).
I have this in XML (used in an <include>):
<com.google.android.gms.ads.AdView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="BANNER"/>
and this in onCreate():
AdView mAdview = (AdView)findViewById(R.id.adView);
mAdview.setAdUnitId(((App)getApplication()).getAdmobKey());
mAdview.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
findViewById(R.id.adView).setVisibility(View.VISIBLE);
}
});
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdview.loadAd(adRequest);
And I get:
The ad size and ad unit ID must be set before loadAd is called.
So the second option was to make the ad programmatically.
The new XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/adView"
/>
The new code:
AdView mAdview = new AdView(this);
...
((LinearLayout)findViewById(R.id.adView)).addView(mAdview);
mAdview.loadAd(adRequest);
But I get the same error.
I tried also to inherit from com.google.android.gms.ads.AdView to make a custom view, but it's final.
Any suggestion?
The method loadAd() checks if (mAdView.getAdSize() == null || mAdView.getAdUnitId() == null) when loadAd happens.
Try logging the boolean output of (mAdView.getAdSize() == null || mAdView.getAdUnitId() == null) before calling loadAd to determine its state:
mAdView = new AdView(this);
mAdView.setAdSize(AdSize.BANNER);
mAdView.setAdUnitId(AD_UNIT_ID);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
if(mAdView.getAdSize() != null || mAdView.getAdUnitId() != null)
mAdView.loadAd(adRequest);
// else Log state of adsize/adunit
((LinearLayout)findViewById(R.id.adView)).addView(mAdview);
If you using ConstraintLayout or CoordinatorLayout solution here
For ConstraintLayout
private AdView mAdView;
private AdRequest mAdRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addAdView();
initAd();
}
private void addAdView() {
ConstraintLayout constraintLayout = findViewById(R.id.constraint_layout);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
mAdView = new AdView(this);
mAdView.setAdSize(AdSize.BANNER);
mAdView.setAdUnitId(getString(R.string.banner1_id));
mAdView.setId(View.generateViewId());
constraintLayout.addView(mAdView);
constraintSet.connect(mAdView.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0);
constraintSet.connect(mAdView.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, 0);
constraintSet.connect(mAdView.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 0);
constraintSet.constrainHeight(mAdView.getId(), ConstraintSet.WRAP_CONTENT);
constraintSet.constrainWidth(mAdView.getId(), ConstraintSet.WRAP_CONTENT);
constraintSet.applyTo(constraintLayout);
}
private void initAd() {
MobileAds.initialize(this, initializationStatus -> {
});
initBanner();
}
private void initBanner() {
mAdRequest = new AdRequest.Builder().build();
mAdView.loadAd(mAdRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
}
#Override
public void onAdOpened() {
super.onAdOpened();
}
});
}
For CoordinatorLayout
private AdView mAdView;
private AdRequest mAdRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addAdView();
initAd();
}
private void addAdView() {
CoordinatorLayout coordinatorLayout = findViewById(R.id.coordinator_layout);
mAdView = new AdView(this);
mAdView.setAdSize(AdSize.BANNER);
mAdView.setAdUnitId(getString(R.string.banner1_id));
CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER | Gravity.BOTTOM;
mAdView.setLayoutParams(params);
mAdView.setId(View.generateViewId());
coordinatorLayout.addView(mAdView);
}
private void initAd() {
MobileAds.initialize(this, initializationStatus -> {
});
initBanner();
}
private void initBanner() {
mAdRequest = new AdRequest.Builder().build();
mAdView.loadAd(mAdRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
}
#Override
public void onAdOpened() {
super.onAdOpened();
}
});
}
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();
}
I have read few articles on trying to stop adView when the app is hidden/minimised but this crashes my app.
This is my code, adView.LoadAd... and adView.stopLoading both crashes the app on startup.
public class MainActivity extends Activity implements OnItemSelectedListener {
#Override
protected void onResume() {
super.onResume();
if (AdViewStarted = true) {
adView.loadAd(new AdRequest());
}
}
#Override
protected void onPause() {
super.onPause();
if (AdViewStarted = true) {
adView.destroy();
}
}
[...]
public class AdMob extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adView = new AdView(this, AdSize.BANNER,"12345678901234567890");
LinearLayout layout = (LinearLayout) findViewById(R.id.adView);
layout.addView(adView);
adView.loadAd(new AdRequest());
AdViewStarted = true;
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
}
}
Thanks in advance
Replace the if statements, you have to use two equals instead of one. Correct would be
if (AdViewStarted == true) {
adView.destroy();
}
or better
if (AdViewStarted) {
adView.destroy();
}
By the win, variable names are starting with a lowercase char.
Also, what are you trying in your onCreate?
This is correct (I think, if not, show me the layout xml file and LogCat):
LinearLayout adView = (LinearLayout) findViewById(R.id.adView);
adView.loadAd(new AdRequest());
AdViewStarted = true;