Thursday, June 18, 2015

Network Connection In Android

Network operations should be performed in a separate thread. The AsyncTask provides one of the simplest ways to fire off a new tasks from the UI thread. 
Application can create one class that is subclass of AsyncTask and implement the doInBackground, onPostExecute methods and return  the results to the UI

A simple implementation of async task will be like this. 

public class HttpConnectorAsyncTask extends AsyncTask {

    private  static final String LOG_TAG = "HCAT";
    private HttpConnectorAsyncTaskListener listener = null;

    public void setConnectionListener(HttpConnectorAsyncTaskListener listener)
    {
        this.listener = listener;
    }

    @Override
   
protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
       
try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    // onPostExecute displays the results of the AsyncTask.
   
@Override
   
protected void onPostExecute(String result) {
//        textView.setText(result);
       
if(this.listener != null)
        {
            this.listener.connectionResponseDataReceived(result);
        }
    }

    private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        // Only display the first 500 characters of the retrieved
        // web page content.
       
int len = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
           
conn.connect();
            int response = conn.getResponseCode();
            Log.d(LOG_TAG, "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
           
String contentAsString = readIt(is, len);
            return contentAsString;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
       
} finally {
            if (is != null) {
                is.close();
            }
        }
    }

    // Reads an InputStream and converts it to a String.
   
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }
}

to note: 

- This method reads only 500 chars 
- upon getting connection error, need to handle cases

References

No comments:

Post a Comment