How to avoid Admob blocking the UI thread
Here is my solution:
public class YHYBackgroundThread extends AsyncTask<Object, Object, Object> {
private YHYBackgroundListener mListener;
private Context context;
public YHYBackgroundThread(Context context) {
this.context= context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Object doInBackground(Object... params) {
if(mListener != null){
return mListener.onBackground(params);
}
return null;
}
@Override
protected void onPostExecute(Object t) {
if (mListener != null) {
mListener.onPostExecute(t);
}
}
public YHYBackgroundThread setListener(YHYBackgroundListener mListener){
this.mListener = mListener;
return this;
}
}
YHYBackgroundListener
public interface YHYBackgroundListener {
Object onBackground(Object... params);
void onPostExecute(Object list);
}
call this, when you need show ads
new YHYBackgroundThread(context).setListener(
new YHYBackgroundListener() {
@Override
public Object onBackground(Object... params) {
AdRequest request = new AdRequest.Builder().build();
return request;
}
@Override
public void onPostExecute(Object list) {
AdRequest request = (AdRequest) list;
adView.loadAd(request);
}
}
).execute();
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);
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");
}