8

我想将我的添加加载到后台线程上,因为它SlidingMenu在打开和关闭时会变得迟钝。我应该使用Thread/Handler吗?或者AsyncTask

String MY_AD_UNIT_ID = "----";
AdView adView = new AdView(getActivity(), AdSize.BANNER, MY_AD_UNIT_ID);
final LinearLayout adLayout = (LinearLayout) getActivity()
            .findViewById(R.id.adLayout);
adLayout.addView(adView);
adView.loadAd(new AdRequest());
4

3 回答 3

12

这可以通过在 UI 线程上加载广告来实现runOnUiThread

从这里调用onCreate()

    Thread adThread = new Thread()
    {
        @Override
        public void run()
        {
            loadAd();
        }
    };
    adThread.start();

loadAd()方法

private void loadAd()
{
    // Banner Ad
    final AdView adview = (AdView) this.findViewById(R.id.adview);

    // Request for ads
    final AdRequest adRequest = new AdRequest.Builder()
            // Time for test devices
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .addTestDevice("xxxxxxxxxxxxxxxxxxxxxxx")
            .addTestDevice("xxxxxxxxxxxxx")
            .build();

    // Load Ads on UI Thread
    runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            adview.loadAd(adRequest);
        }
    });
}
于 2015-08-10T21:34:06.043 回答
6

您应该在广告加载之前使用MobileAds.initialize()方法。之后 loadAd 工作得更快

Initializes the Google Mobile Ads SDK.

Call this method as early as possible after the app launches to reduce latency on the session's first ad request.

If this method is not called, the first ad request automatically initializes the Google Mobile Ads SDK.
于 2017-05-26T17:43:09.373 回答
3

我不相信这可以完成,因为所有与 UI 相关的东西都必须在主线程上完成。API 可能已经有一个线程来获取网络上的广告。NetworkOnMainThreadException如果它没有,如果在主线程上完成了任何与网络相关的事情,android 会抛出一个

于 2013-06-25T21:03:59.167 回答