简体   繁体   中英

doInBackground in AsyncTask for Android

I want to know that if a doInBackground method of a AsyncTask calls a method, for example XYZ() , Is that method also executed asynchronously?

Can we make changes to the UI in XYZ() in such a situation? Will it make the UI unresponsive?

I have a method call in doInBackground which is network intensive and requires to download an image from the web. The UI becomes unresponsive as soon as the call to that method is made. Why?

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;
}

The method getRandomImageURL and all that code in the try block is network intensive. I can also provide its code.

The code executing in the background is run in a separate thread. Anything it does, including calling other methods, happens in that thread. Since this is not the UI thread, it's not valid to make UI calls. You have to post messages to the UI thread.

Yes, whatever you call within doInBackgroud will run asynchronously. And no you shoudn't update UI from background thread for that you have CallBackDefined(onPostExecute). Or if UI update is require you can use runOnUIThread(...) API

You can make changes to the UI only from the UI thread. In general the doInBackground() is for lengthy operations that do not update the UI or access the UI toolkit. You can periodically publish changes in state that need to be reflected in the UI (eg progress bar showing status of a download operation) by calling publishProgress().

Set time out like this...

HttpPost httppost = new HttpPost(url);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httppost);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM