我想知道如果AsyncTask
的doInBackground
方法調用方法,例如XYZ()
,那麼該方法是否也異步執行?Android的AsyncTask中的doInBackground
在這種情況下,我們可以更改XYZ()中的用戶界面嗎?它會使界面無響應?
我有一個方法調用doInBackground
這是網絡密集型的,需要從網上下載圖片。只要對該方法進行調用,UI就會無響應。爲什麼?
protected String[] doInBackground(String... params)
{
String[] response = new String[2];
Log.v("Background", "I am in background!");
String url = params[0];
String VoiceInput = params[1];
IsCalledOnVoiceInput = VoiceInput;
Log.v(url,url);
HttpPost httppost = new HttpPost(url);
try
{
HttpParams p = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(p);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
responseBody = httpclient.execute(httppost,
responseHandler);
Log.v("Thread", responseBody);
//Getting background image URL
JSONObject reader = new JSONObject(responseBody);
JSONObject coords = reader.getJSONObject("coord");
loc_latitude = coords.getString("lat");
loc_longitude = coords.getString("lon");
String imageURL="";
/////////////////////////////////////////////////////////////////////////////////
try
{
imageURL = getRandomImageURL(loc_latitude,loc_longitude);
Log.v("Image URL as recieved from getRandomImageURL", imageURL);
//Trying to convert Image from the above URL, get it and theh convert it to String
URL urlOfTheImage = new URL(imageURL);
bmp = BitmapFactory.decodeStream(urlOfTheImage.openConnection().getInputStream());
//Image successfully converted to string, ready to pass as a parameter!
response[0] = "";
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"There seems to be a problem with the application. Please try again later.", Toast.LENGTH_LONG).show();
}
Log.v("URL of Random Image",imageURL);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
response[1] = responseBody;
return response;
}
方法getRandomImageURL
和所有代碼在try
塊是網絡密集的。我也可以提供它的代碼。
任何稱爲'doInBackground'方法將被異步調用。你不應該改變那裏的用戶界面。 – Rohit5k2
檢查更新的問題。 –
請發佈您的代碼的適當部分。已添加代碼 – Rohit5k2