Search code examples
androidmultithreadingviewadmob

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


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();
        }
    }
}

Solution

  • so for so many research i found another way of solution by using timer which will work for me

    Adapting this answer:

    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();
                        
                        
                    }
                });