I’ve got this setup and working with a help of a friend. It works 95% of the time.
But at times, Ads don’t disappear when they are supposed to disappear. Like it loss’s Sync. I’m not sure what the bug might be.
//C++ SIDE
#include “SDL.h”
#include <jni.h>
#include “ads.h”
ads::ads()
{
bAds = false;
}
void ads::callJava(const char* methodName) const {
// retrieve the JNI environment.
JNIEnv* env = (JNIEnv*) SDL_AndroidGetJNIEnv();
// retrieve the Java instance of the SDLActivity
jobject activity = (jobject) SDL_AndroidGetActivity();
// find the Java class of the activity. It should be SDLActivity or a subclass of it.
jclass clazz(env->GetObjectClass(activity));
// find the identifier of the method to call
jmethodID method_id = env->GetMethodID(clazz, methodName, "()V");
// effectively call the Java method
env->CallVoidMethod(activity, method_id);
// clean up the local references.
env->DeleteLocalRef(activity);
env->DeleteLocalRef(clazz);
// Warning (and discussion of implementation details of SDL for Android):
// Local references are automatically deleted if a native function called
// from Java side returns. For SDL this native function is main() itself.
// Therefore references need to be manually deleted because otherwise the
// references will first be cleaned if main() returns (application exit).
}
void ads::showAds()
{
if (bAds == false)
{
callJava(“showAds”);
bAds = true;
}
}
void ads::hideAds()
{
if (bAds == true)
{
callJava(“hideAds”);
bAds = false;
}
}
////////JAVA SIDE
public void showAds() {
// Log.d(“TIM”, “showAds() called.”);
if (adView == null) {
final FrameLayout root = (FrameLayout) findViewById(R.id.realRoot);
root.post(new Runnable() {
public void run() {
Log.i("TIM", "showAds().");
reallyShowAds(root);
}
});
}
// Log.d("TIM", "showAds() done.");
}
private void reallyShowAds(final FrameLayout root)
{
if (adView == null)
{
adView = new AdView(SDLActivity.this);
//adView.setVisibility(View.VISIBLE);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // test ad code
AdRequest adRequest = new AdRequest.Builder().build();
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
50,
Gravity.TOP | Gravity.CENTER);
adView.setLayoutParams(lp);
root.addView(adView, lp);
adView.loadAd(adRequest);
}
}
public void hideAds()
{
// Log.d("TIM", "hideAds() called.");
if (adView != null)
{
//adView.pause();
final FrameLayout root = (FrameLayout) findViewById(R.id.realRoot);
root.post(new Runnable()
{
public void run()
{
Log.i("TIM", "hideAds().");
reallyHideAds();
}
}); // });
}
// Log.d("TIM", "hideAds() done.");
}
private void reallyHideAds()
{
if (adView != null)
{
//adView.setVisibility(View.GONE);
//adView.setVisibility(View.INVISIBLE);
adView.destroy();
adView = null;
}
}