How to avoid Admob blocking the UI thread

后端 未结 4 1570
忘了有多久
忘了有多久 2020-12-16 18:04

I have detected some of my activities are blocked at the launch. So I wrote that code in a new project:

public class LayoutTestActivity extends Activity {

          


        
相关标签:
4条回答
  • 2020-12-16 18:24

    Use threads:

    public class LayoutTestActivity extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        long now = System.currentTimeMillis();
    
        new Thread(new Runnable() {
    
            public void run() {
                new AdView(this, AdSize.BANNER, "MY_ID");               
            }
        }).start();
    
        Log.e("Admob Test","The UI was blocked "+(System.currentTimeMillis()-now)+"ms");
    }
    
    0 讨论(0)
  • 2020-12-16 18:28

    In my case I requested too much advertisement items in one request. The heap is overloaded and GC started action and it blocked my Main thread. The piece of advice try to avoid requesting too much Ad in one request.

    adLoader.loadAds(AdRequest.Builder().build(), 1)
    
    0 讨论(0)
  • 2020-12-16 18:43

    You are creating your AdView in your UI thread which is the reason for getting blocked. While the AdView initilization takes place the thread wont do anything else.

    You can try loading your AdView in another thread or can use a AsyncTask to load it in a UI safe way.

    Check this for more info about AsyncTask and Threading in Android.

    http://developer.android.com/reference/android/os/AsyncTask.html

    0 讨论(0)
  • 2020-12-16 18:43

    I had a similar issue. Resolved it by delaying the ad-request for 1 second (which gives time for the AdView to load and not block the UI.

            new Timer().schedule(new TimerTask()
            {
                @Override
                public void run()
                {
                    MainActivity.runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            AdRequest adRequest = new AdRequest.Builder()
                                    .addTestDevice(AD_TEST_DEVICE)
                                    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                                    .build();
    
                            adView.loadAd(adRequest);
                        }
                    });
                }
            }, 1000);
    
    0 讨论(0)
提交回复
热议问题