我一直在关注本教程:https://github.com/libgdx/libgdx/wiki/Admob-in-libgdx 我确定我已经正确地实现了所有内容,并且仍然为处理程序获取空指针。教程中的代码有问题吗?
这是我的Android启动码:
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);
}
}
我的游戏类:
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();
}
}
最后是ReqestHandler:
public interface IActivityRequestHandler {
public void showAds(boolean show);
}
答案 0 :(得分:0)
问题如下:
您的AdView
对象是在onCreate()
类的AndroidLauncher
函数内本地定义的。然后,您尝试在onCreate()
对象中的Handler
之外访问它。 AdView
对象超出范围。您应该在AdView
之外的AndroidLauncher
课程中声明onCreate()
:
AdView adView;
然后在onCreate()
中你可以像你一样实例化它:
// 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());