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
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
Answer:
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);
Answer:
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");
}
Tags: javajava