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);
}
}
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();
}
}
I am implementing admob banner ad in the libgdx game. I have made several screens and want to show banner ad on each and every screen. I implemented banner ad in the launcher class and trying to show it in the screen class through the interface method calling, but the application is crashing every time with the error.
4-22 20:47:14.466 24246-24280/com.mygdx.game E/AndroidRuntime: FATAL EXCEPTION: GLThread 80476
Process: com.mygdx.game, PID: 24246
java.lang.NullPointerException: Attempt to invoke interface method 'void com.mygdx.game.AdsController.showBannerAd()' on a null object reference
at com.mygdx.game.BabyOrange.create(BabyOrange.java:51)
at com.mygdx.game.BabyScreen.<init>(BabyScreen.java:38)
at com.mygdx.game.BabyOrange.<init>(BabyOrange.java:42)
at com.mygdx.game.BabyGame.create(BabyGame.java:9)
at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:311)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1633)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1354)
Here is the code for the launcher and the screen class
public class BabyOrange extends BabyScreen {
private BabyActor bg;
private BabyActor ph;
private AdsController adsController;
public BabyOrange(Game g,AdsController adsController){
super(g);
this.adsController = adsController;
}
public void create () {
adsController.showBannerAd();
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());
}
Here is the interface
public interface AdsController {
public void showBannerAd();
public void hideBannerAd();
}
And the Android launcher class
public class AndroidLauncher extends AndroidApplication implements AdsController{
private static final String BANNER_ID = "ca-app-pub-959117648XXXXXX/XXXXXXXX";
AdView bannerAd;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
//create a gameView and a bannerAd AdView
View gameView = initializeForView(new BabyGame(), 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_BOTTOM);
layout.addView(bannerAd,params);
setContentView(layout);
}
public void setupAds(){
bannerAd = new AdView(this);
bannerAd.setVisibility(View.INVISIBLE);
bannerAd.setAdUnitId(BANNER_ID);
bannerAd.setAdSize(AdSize.SMART_BANNER);
}
#Override
public void showBannerAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
bannerAd.setVisibility(View.VISIBLE);
AdRequest.Builder builder = new AdRequest.Builder();
AdRequest ad = builder.build();
bannerAd.loadAd(ad);
}
});
}
#Override
public void hideBannerAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
bannerAd.setVisibility(View.INVISIBLE);
}
});
}
}
Your super constructor calls the underlying create function before your adsController is set. Try this code:
public BabyOrange(Game g,AdsController adsController){
super(g);
this.adsController = adsController;
create2();
}
public void create2() {
adsController.showBannerAd();
}
public void create () { // called within super-constructor
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());
}
...
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());
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);
Iam trying to add unityview as subview in android layout.
I create relative layout in android xml file and added unityview to relativelayout.
But the unityview is appearing as small image at left bottom of relative layout.
The black portion is my relativelayout but unity view not occupying enter relative layout.
The code is as follows:
public class MainActivity extends UnityPlayerActivity {
public static Context mContext;
private Handler handler=new Handler();
private UnityPlayer m_UnityPlayer;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
mContext = this;
m_UnityPlayer = new UnityPlayer(this);
int glesMode = m_UnityPlayer.getSettings().getInt("gles_mode", 1);
boolean trueColor8888 = false;
m_UnityPlayer.init(glesMode, trueColor8888);
setContentView(R.layout.activity_main);
//This is my relative layout
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativelayout2);
//Relativelayout width is 750dp and height is 640dp.
LayoutParams lp = new LayoutParams (750, 640);
//Iam adding unityview to layout here
layout.addView(m_UnityPlayer.getView(), 0, lp);
}
}
Finally I got the solution.
MainActivity should be extend as Activity, not UnityPlayerActivity.
Add these two lines to activity in android manifest
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
<meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="false" />
The working code is:
public class MainActivity extends Activity implements OnTouchListener {
public static Context mContext;
private Handler handler=new Handler();
protected UnityPlayer mUnityPlayer;
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
mContext = this;
getWindow().takeSurface(null);
setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
getWindow().setFormat(PixelFormat.RGB_565);
mUnityPlayer = new UnityPlayer(this);
if (mUnityPlayer.getSettings ().getBoolean ("hide_status_bar", true))
getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
int glesMode = mUnityPlayer.getSettings().getInt("gles_mode", 1);
boolean trueColor8888 = false;
mUnityPlayer.init(glesMode, trueColor8888);
View playerView = mUnityPlayer.getView();
setContentView(R.layout.activity_main);
FrameLayout layout = (FrameLayout) findViewById(R.id.frameLayout2);
LayoutParams lp = new LayoutParams (750, 630);
layout.addView(playerView, 0, lp);
}
protected void onDestroy ()
{
mUnityPlayer.quit();
super.onDestroy();
}
// onPause()/onResume() must be sent to UnityPlayer to enable pause and resource recreation on resume.
protected void onPause()
{
super.onPause();
mUnityPlayer.pause();
}
protected void onResume()
{
super.onResume();
mUnityPlayer.resume();
}
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mUnityPlayer.configurationChanged(newConfig);
}
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
mUnityPlayer.windowFocusChanged(hasFocus);
}
public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_MULTIPLE)
return mUnityPlayer.onKeyMultiple(event.getKeyCode(), event.getRepeatCount(), event);
return super.dispatchKeyEvent(event);
}
}
The result: