how to call the onBackPress() on the main thread of the process - android

I am new to admobi, I am adding interstitial adds, I want to close the add programmatically. After some research I found that it is not possible ,only this we need use onbackpress to close the add ,as it will closes when you press the backpress key .i have tried it but it is giving an error like
java.lang.IllegalStateException: Must be called from main thread of process.
at android.app.Activity.onKeyUp(Activity.java:2131)
i am trying to solve it from the lost two days it is not working please any body solve it and give it to me will be thank full.i am adding my code below
public class MainActivity extends Activity {
private InterstitialAd interstitial;
protected boolean active = true;
protected int splashtime = 3000;
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
//super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Prepare the Interstitial Ad
interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
interstitial.setAdUnitId("ca-app-pub-4412961323059248/9600290618");
final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = tm.getDeviceId();
//Locate the Banner Ad in activity_main.xml
AdView adView = (AdView) this.findViewById(R.id.adView);
// Request for Ads
AdRequest adRequest = new AdRequest.Builder()
// Add a test device to show Test Adss
/* .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("9F0D0FB0280794109822A582BFFB7EC1")*/
.build();
// Load ads into Banner Ads
adView.loadAd(adRequest);
// Load ads into Interstitial Ads
interstitial.loadAd(adRequest);
Thread splash = new Thread()
{
#Override
public void run()
{
// TODO Auto-generated method stub
super.run();
try
{
int waitid = 0;
while(active && (waitid < splashtime))
{
sleep(1000);
if(active)
{
waitid+=100;
}
}
}
catch (InterruptedException e)
{
// TODO: handle exception
}
finally
{
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
}
}
};
splash.start();
// Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
// Call displayInterstitial() function
//interstitial.show();
displayInterstitial();
}
});
}
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}

so for so many research i found another way of solution by using timer which will work for me
Timer timer = new Timer();
SwitchPage(6);
private void SwitchPage(int seconds) {
// TODO Auto-generated method stub
timer = new Timer(); // At this line a new Thread will be created
timer.schedule(new SwitchPageTask(), 10000, seconds * 10000); // delay in milliseconds
}
class SwitchPageTask extends TimerTask {
#Override
public void run() {
// As the TimerTask run on a separate thread from UI thread we have
// to call runOnUiThread to do work on UI thread.
runOnUiThread(new Runnable() {
public void run() {
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
finish();
SwitchPageTask.this.cancel();
Intent intent=new Intent(MainActivity.this,Second.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
SwitchPageTask.this.cancel();
finish();
}
});

Implement key_up and key_down events inside Handler of main thread.
From inside your splash thread, send a message to the implemented handler to execute the key_up and key_down events.
import android.os.Handler;
public class MainActivity extends Activity {
private InterstitialAd interstitial;
protected boolean active = true;
protected int splashtime = 3000;
private Handler handler;
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
//super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
//Creating new Handler object
handler = new Handler(){
#Override
public void handleMessage(Message msg) {
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
}
};
// Prepare the Interstitial Ad
interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
interstitial.setAdUnitId("ca-app-pub-4412961323059248/9600290618");
final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = tm.getDeviceId();
//Locate the Banner Ad in activity_main.xml
AdView adView = (AdView) this.findViewById(R.id.adView);
// Request for Ads
AdRequest adRequest = new AdRequest.Builder()
// Add a test device to show Test Adss
/* .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("9F0D0FB0280794109822A582BFFB7EC1")*/
.build();
// Load ads into Banner Ads
adView.loadAd(adRequest);
// Load ads into Interstitial Ads
interstitial.loadAd(adRequest);
Thread splash = new Thread()
{
#Override
public void run()
{
// TODO Auto-generated method stub
super.run();
try
{
int waitid = 0;
while(active && (waitid < splashtime))
{
sleep(1000);
if(active)
{
waitid+=100;
}
}
}
catch (InterruptedException e)
{
// TODO: handle exception
}
finally
{
handler.sendEmptyMessage(0);
}
}
};
splash.start();
// Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
// Call displayInterstitial() function
//interstitial.show();
displayInterstitial();
}
});
}
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}

calll this where you want to perform backpress from your activity
super.onBackPressed();

Related

How to show Interstitial ads after x seconds on app

I set an insterstitital add that shows inmediatelly when the app is opened but I would like it to appear lets say after a minute.
Here is the part of my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
interstitial = new InterstitialAd(MainActivity.this);
interstitial.setAdUnitId("ca-app-pub-XXXXXXXXXXXXXXXXXXXXXXXXXX");
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
interstitial.loadAd(adRequest);
// Bind to the service
try {
bindIntent = new Intent(this, RadioService.class);
bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) {
}
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (telephonyManager != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
handler = new Handler();
initialize();
// Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
// Call displayInterstitial() function
displayInterstitial();
}
});
}
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
interstitial.show();
}
}
Help is welcome!!
Thank you in advance!
you can use a Handler for that:
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
displayInterstitial();
}
},60000);
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
}
Here 60000 is time in ms
so if you need for 20 mins then 60000*20

build AdMob Interstitial ad again after 60 seconds

Currently, I am using the code which is displaying AdMob Interstitial ad after 20 seconds and when the ad is closed I want to show another ad after 60 seconds, this is the code currently I am using for the first ad to load after 20 seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
interAd = new InterstitialAd(MainActivity.this);
interAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.build();
interAd.loadAd(adRequest);
interAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
interAd.show();
}
});
interAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Code to be executed when the interstitial ad is closed.
Log.i("Ads", "onAdClosed");
}
});
}
} , 20000);
i have tried this method from AdMob tutorial it load the ads but after every second
interAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
interAd.loadAd(new AdRequest.Builder().build());
}
});
You should attach you Ad's lifecycle to your Activity's lifecycle so you can start/stop showing adds just when your app is visible to the user.
Create a global variables for you Ad and Handler
private InterstitialAd mInterstitialAd;
private Handler mHandler = new Handler();
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
// Wait 60 seconds
mHandler.postDelayed(this, 60*1000);
// Show Ad
showInterstitial();
}
};
then...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the InterstitialAd and set the adUnitId
mInterstitialAd = newInterstitialAd();
loadInterstitial();
}
#Override
protected void onStart() {
super.onStart();
// Start showing Ad in every 60 seconds
//when activity is visible to the user
mHandler = new Handler();
//mHandler.post(mRunnable);
// Run first add after 20 seconds
mHandler.postDelayed(mRunnable,20*1000);
}
protected void onStop() {
super.onStop();
// Stop showing Ad when activity is not visible anymore
mHandler.removeCallbacks(mRunnable);
}
private void loadInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
private InterstitialAd newInterstitialAd() {
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mNextLevelButton.setEnabled(true);
}
#Override
public void onAdFailedToLoad(int errorCode) {
mNextLevelButton.setEnabled(true);
}
#Override
public void onAdClosed() {
// Reload ad so it can be ready to be show to the user next time
mInterstitialAd = newInterstitialAd();
loadInterstitial();
}
});
return interstitialAd;
}
private void showInterstitial() {
// Show the ad if it's ready. Otherwise toast and reload the ad.
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
mInterstitialAd = newInterstitialAd();
loadInterstitial();
}
}
Make a new thread, then add a sleep time of 60000 milliseconds before showing your ad back. It will allow for async working.
Example, add this code in the onAdClosed() :
new Thread(new Runnable(){
public void run(){
Thread.sleep(60000);
// Show your ad here
}
}).start();

Press Double Back To Exit

Android Webview
current code in my app works like this:
When user press back single time it will shows button asking "Do you want to quit?" shows yes or no options. when we select Yes it exit app and show interstitial ad. if you press No it will remains in the activity.
What I want is:
When user press back it will go to previous activity. If user double tap back button then it will ask for exit and if user select Yes. user will exit app and interstitial ad appears.
Please help me to solve this issue.
Main Activity:
public class MainActivity extends Activity{
private Fragment contentFragment;
String testDevice = "D0A04359EA1ECE9BA0CD4B6F457A9991";
String testDevice2 = "63C3530DA03C191310DB9AB8F0672E5C";
String testDevice3 = "801F2141A1DC3F743363AFDFDC42AF3A";
private InterstitialAd mInterstitialAd;
private AdView mAdView;
boolean displayAd = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mainWebView.loadUrl(this.getString(R.string.channel_url));
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(testDevice)
.addTestDevice(testDevice2)
.addTestDevice(testDevice3)
.build();
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
displayAd = true;
// View servername = findViewById(R.id.txt_List);
// RelativeLayout.LayoutParams layoutparams =
(RelativeLayout.LayoutParams) servername.getLayoutParams();
// layoutparams.addRule(RelativeLayout.BELOW, mAdView.getId());
// layoutparams.removeRule(RelativeLayout.ALIGN_PARENT_TOP);
// servername.setLayoutParams(layoutparams);
}
#Override
public void onAdFailedToLoad(int errorCode) {
if (!displayAd) {
}
}
#Override
public void onAdClosed() {
// Proceed to the next level.
}
});
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
// Create the InterstitialAd and set the adUnitId (defined in values/strings.xml).
mInterstitialAd = newInterstitialAd();
loadInterstitial();
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private InterstitialAd newInterstitialAd() {
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
}
#Override
public void onAdFailedToLoad(int errorCode) {
}
#Override
public void onAdClosed() {
// Proceed to the next level.
finish();
//goToNextLevel();
}
});
return interstitialAd;
}
private void showInterstitial() {
// Show the ad if it's ready. Otherwise toast and reload the ad.
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void loadInterstitial() {
// Disable the next level button and load the ad.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(testDevice)
.addTestDevice(testDevice2)
.addTestDevice(testDevice3)
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof EmpListFragment or if the stack entry count is == 0, then
* we prompt the user whether to quit the app or not by displaying dialog.
* In other words, from EmpListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
onShowQuitDialog();
}
public void onShowQuitDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do You Want To Quit?");
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
showInterstitial();
}
});
builder.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
}
This is the easiest code possible:
private static final int TIME_DELAY = 2000;
private static long back_pressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onBackPressed() {
if (back_pressed + TIME_DELAY > System.currentTimeMillis()) {
super.onBackPressed();
} else {
Toast.makeText(getBaseContext(), "Press once again to exit!",
Toast.LENGTH_SHORT).show();
}
back_pressed = System.currentTimeMillis();
}
}
A temp flag will do the thing.
add this code in your onBackPressed() method.
boolean isSecond;
#Override
public void onBackPressed(){
if (isSecond) {
// Open your dialog here
}
isSecond = true;
new Handler() . postDelayed(new Runnable() {
#Override
public void run(){
isSecond = false;
}
}, 2000);
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
onShowQuitDialog();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Try following code :
int backFlag = 0;
#Override
public void onBackPressed() {
backFlag ++;
if(backflag == 1){
super.onBackPressed();
// go to previous activity
}
else if(backFlag == 2){
// ask user to exit
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
backFlag=0;
}
}, 2000);
}
There is no built-in function for double onBackPressed() so you have to construct your own version of it. The android system provides a Handler on which you can call postDelayed to measure the time between two and one click.
e.g. like this
boolean backPressed = false;
boolean backPressedTwice = false;
#Override
public void onBackPressed() {
if(!backPressed){
backPressed = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(!backPressedTwice)
MainActivity.this.finish(); // go back to previous activity
}
}, 500);
}
if(backPressed) {
// it's clicked twice
backPressedTwice = true; // cancel the handler so it does not finish the activity
onShowQuitDialog();
}
}
Demo for your task:
public class MainActivity extends AppCompatActivity {
Handler handler = new Handler();
boolean ShowDialog = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler(getMainLooper());
}
#Override
public void onBackPressed() {
if (!ShowDialog) {
this.ShowDialog = true;
handler.postDelayed(runnable, 2000);// time setting .. current is 2 sec
} else {
handler.removeCallbacks(runnable);
ShowDialog = false;
ShowDailog();
}
}
private void ShowDailog() {
Toast.makeText(this, "show dialog here", Toast.LENGTH_LONG).show();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
ShowDialog = false;
MainActivity.super.onBackPressed();
}
};
}
You can do something like this
private long backPressedTime = 0;
private long backPressThreshold = 400;
private Handler mHandler = new Handler();
private Runnable bacPressedRunnable = new Runnable() {
#Override
public void run() {
MYActivity.super.onBackPressed();
}
};
#Override
public void onBackPressed() {
if(backPressedTime = 0){
backPressedTime = Systemm.currentTimeInMillis();
mHandler.postDelayed(bacPressedRunnable,backPressThreshold);
}else if(System.currentTimeInMillis()-backPressedTime >= backPressThreshold){
mHandler.removeMessages(bacPressedRunnable);
onShowQuitDialog();
}else{
super.onBackPressed();
}
backPressedTime = 0;
}
Exit android App on double back press use following updated code. It may solve your problem
private boolean doubleBackToExitPressedOnce;
private void onApplicationBackPressed() {
if (doubleBackToExit) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
return;
}
doubleBackToExit= true;
Utilities_dialer.showToastMessage(this, "Press Again To Exit");
//use your dialog box or toast message
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExit= false;
}
}, 2000);
}
Try this.. It may help you.
Boolean doubleBackToExitPressedOnce = true;
#Override
public void onBackPressed() {
if(doubleBackToExitPressedOnce){
// Do what ever you want
doubleBackToExitPressedOnce = false;
} else{
// Do exit app or back press here
super.onBackPressed();
}
}

Admob Add shown in Delay Time

public class MainActivity extends Activity {
AdView adView;
InterstitialAd interstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adView = (AdView) findViewById(R.id.adView);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId("ca-app-pub-3500425325579414/2869090680");
AdRequest adRequest = new AdRequest.Builder().addTestDevice(
"BD9386F17F7DE795B86B5BBBEDDF1095").build();
adView.loadAd(adRequest);
interstitialAd.loadAd(adRequest);
interstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
}
}
});
Thread timerThread = new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
sleep(5000);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
?????????????????????
}
}
};
timerThread.start();
}
}
I want to show my Admob add after my selected time.
I want to use a Thread to show my add in dealy.
But how i complite this i could not do it.
Even i tryed this
Thread timerThread = new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
sleep(5000);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
interstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
}
}
});
}
}
};
timerThread.start();
But this is not working.
How i can do it in programatically.
The problem I see is that you are setting the Adlistener after a delay instead of showing the ad after a delay.
Also you don't need to create a Thread for doing that, you can try this for example:
interstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
MainActivity.this.interstitialAd.show();
}
}, 5000);
}
});
Put this in your MainActivity onCreate method and get rid of the timerThread. This way you'll have your interstitial configured that it will show up 5 sec after the ad is loaded.
Note: From user a user experience point of view that is not such a good idea because you'll most likely end up annoying your users. The best practice is to show ads at natural breaks, like "level completed" etc.
You DON'T want to show your interstitial ads at random (delayed or not) time within your app. Unless
You want really bad user ratings
You want Admob to disable your account.
Instead you should pick a suitable break point in your app and show the ad then.

Admob Interstitial ad is not clickable in android app exit

I am trying to show admob interstitial ad at the end of the application when user presses back button from the main activity. Ad is shown, but the ad is not clickable. My code is
I put loading part at the activity onCreate :
interstitial = new InterstitialAd(getApplicationContext());
interstitial.setAdUnitId("Ad UNIT ID");
// Create ad request.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
and in OnBackPressed :
#Override
public void onBackPressed() {
super.onBackPressed();
displayInterstitial();
}
protected void displayInterstitial() {
Log.d(TAG, "start displayInterstitial()");
if (null != interstitial && interstitial.isLoaded()) {
Log.d(TAG, "displayInterstitial() loaded");
interstitial.show();
}
Log.d(TAG, "end displayInterstitial()");
}
Can anyone please help me to fix this issue?
Simplest way would be:
interstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
finish();
}
});
However, in my opinion it is better to stay at your app for a sec before app finishes. That way it is more clear that this ad was still part of your app:
interstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finish();
}
}, 1000);
}
});
BTW: about the comment of calling MainActivity.super.onBackPressed(); inside the adlistener's onAdClosed: I tested it and threw an IllegalStateException. I guess that is because the moment when onBackPressed is called is too late already. But well it is anyway not needed, so forget about it. The super onBackPressed method itself is accessible from the AdListener though and will compile just fine ;-)
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed Called");
displayInterstitial();
//finish();
super.onBackPressed();
}

Categories

Resources