安卓 2.3.3
我正在将 AD 服务集成到我客户的一个应用程序中。
这是我在 AsyncTask 中所做的:
- 构造一个查询并使用 HTTP Get 方法以所需的宽度和高度以及其他参数查询服务器。
- 从服务器获得响应后,我必须在主线程上更新它(将响应附加为 HTML 标记)。
问题是广告是随机显示的。这与网络问题有关还是与我的代码有关?而且,如果使用DefaultHTTPClient
和其他任何东西一样好?
主要活动中的代码:
private static GetMMediaAdsTask mGetMMediaAds;
static String responseBody = "";
StringBuffer html = new StringBuffer();
....
....
html.append("<p>");
String url = "http://xxxx.com/getAd";
mGetMMediaAds = new GetMMediaAdsTask(context);
mGetMMediaAds.execute(url); // Calling the execute method of asynctask
...
...
...
html.append(responseBody);
html.append("</p>");
AsyncTask 子类
public static class GetMMediaAdsTask extends AsyncTask<String, Void, Boolean>{
String url = "http://ads.mp.mydas.mobi/getAd";
String apid = "123xxx";
String auid = "";
String returned = "";
private Context mContext;
public GetMMediaAdsTask(Context context) {
// TODO Auto-generated constructor stub
mContext = context;
}
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("***** Inside AsyncTask *****");
auid = Secure.getString(mContext.getContentResolver(), Secure.ANDROID_ID);
int hsht = 0;
int hswd = 0;
DisplayMetrics metrics = new DisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
System.out.println("Height ="+height+" Width = "+width);
if(width <= 320)
{
hswd = 320;
hsht = 53;
}
else if(width > 320 && width < 468)
{
hswd = 320;
hsht = 53;
}
else if(width >= 468 && width < 728)
{
hswd = 468;
hsht = 60;
}
else if(width >= 728)
{
hswd = 728;
hsht = 90;
}
String query = String.format("apid=%s&auid=%s&hsht=%d&hswd=%d", apid, auid, hsht, hswd);
System.out.println("query = "+query);
try {
DefaultHttpClient http = new DefaultHttpClient();
HttpGet httpMethod = new HttpGet();
httpMethod.setURI(new URI(url + "?" + query));
HttpResponse response = http.execute(httpMethod);
int responseCode = response.getStatusLine().getStatusCode();
switch (responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if (entity != null) {
returned = EntityUtils.toString(entity);
System.out.println("response = "+returned);
}
break;
}
} catch (Exception e) {
System.out.println("Exception occured");
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
System.out.println("***** Inside PostExecute *****");
responseBody = returned;
super.onPostExecute(result);
}
}