Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

android - How to create Http Connection using AsyncTask class?

I am trying to create HTTP connection using AsyncTask class.

Is it possible to create HTTP connection ?

Can you suggest sample source code ?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As an inner class inside your activity :

public final class HttpTask
        extends
        AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {

    private HttpClient mHc = new DefaultHttpClient();

    @Override
    protected String doInBackground(String... params) {
        publishProgress(true);
        // Do the usual httpclient thing to get the result
        return result;
    }

    @Override
    protected void onProgressUpdate(Boolean... progress) {
        // line below coupled with 
        //    getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS) 
        //    before setContentView 
        // will show the wait animation on the top-right corner
        MyActivity.this.setProgressBarIndeterminateVisibility(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        publishProgress(false);
        // Do something with result in your activity
    }

}

Then somewhere in your activity :

new HttpTask().execute(someParams...);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...