我試圖實現異步訪問互聯網使用AsyncTask
,但在日誌貓PID
和TID
我的日誌是相同的,因爲AsyncTask不創建並行隊列,所以我的應用程序崩潰與NetworkOnMainThreadException
。AsyncTask Android主線程
這裏是我的子類代碼:
class BL_SimpleAsyncTask extends AsyncTask<Void, Void, Void> {
String requestServer;
HashMap<String, String> postRequestBody;
//------------------------// answer from http client
static DefaultHttpClient sharedClient = null;
boolean isPostRequest;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
System.out.println("bg started");
if (sharedClient == null) {
sharedClient = new DefaultHttpClient();
}
HttpPost post = new HttpPost(requestServer);
String postBody = new String();
postBody += "{";
for (String key : postRequestBody.keySet()) {
String result = String.format("\"%s\":\"%s\",", key, postRequestBody.get(key));
postBody += result;
}
System.out.println("body initialized");
postBody.substring(0, postBody.length() - 1);
postBody += "}";
try {
post.setEntity(new StringEntity(postBody));
} catch (UnsupportedEncodingException e) {
System.out.println(e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("entity set");
try {
if (post != null) {
System.out.println("starting request....");
HttpResponse response = sharedClient.execute(post);
System.out.println("responce recieved");
} else {
System.out.println("null request");
}
// System.out.println(response) ;
} catch (ClientProtocolException e) {
System.out.println(e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
因此,要發動請求後,我只需做到以下幾點:
BL_SimpleAsyncTask obj = new BL_SimpleAsyncTask() ;
obj.requestServer = "https://api.orbios.com/v1/auth/sign-in" ;
obj.postRequestBody = new HashMap<String, String>() ;
obj.postRequestBody.put ("password", password) ;
obj.postRequestBody.put("email", email) ;
obj.isPostRequest = true ;
System.out.println("start bg thread") ;
obj.doInBackground() ;
我在做什麼錯?
謝謝,AsyncTask是一個界面,我忘了!謝謝! – 2014-08-29 13:46:06