How to avoid Admob blocking the UI thread

我与影子孤独终老i 提交于 2019-12-18 15:09:26

问题


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 {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        long now = System.currentTimeMillis();

        new AdView(this, AdSize.BANNER, "MY_ID");

        Log.e("Admob Test","The UI was blocked "+(System.currentTimeMillis()-now)+"ms");
    }
}

And the result is that the first creation of an AdView object blocks the UI thread for between 1 and 2 seconds.

Is there some way of avoiding that?

Thanks


回答1:


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




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/9472674/how-to-avoid-admob-blocking-the-ui-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!