Showing posts with label Network. Show all posts
Showing posts with label Network. Show all posts

Sunday, June 10, 2012

Checking network connection and performing operation in Thread

My this post is related to checking network connection  and how to handle if network connection is not available to make our application more responsive. Later on we will learn how to perform time taking operation in separate thread if connection is present.

First of all we two permission if your are checking wifi connection then you need one extra permission

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
If you want to check connection on click of particular button you can  call this function inside click listener of button

public void ahmadNetworkHanlder() {
 
ConnectivityManager connMgr = (ConnectivityManager)
        getSystemService
(Context.CONNECTIVITY_SERVICE);
   
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
   
if (networkInfo != null && networkInfo.isConnected()) {
       
// fetch data here as network is availble
   
} else {
       
// display error dialog to notify user ,connection is not present
   
}
}
Now consider case, Network is available. Use one asynchronous task to perform network operation like downloading data



public class AhmadActivity extends Activity {
   
private static final String DEBUG_TAG = "AhmadHttp";
   
private EditText urlText;
   
private TextView textView;
   
   
@Override
   
public void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView
(R.layout.main);  
        urlText
= (EditText) findViewById(R.id.myUrl);
        textView
= (TextView) findViewById(R.id.myText);
   
}
// Call this method on Click of A button
  public void ahmadNetworkHandler() {
       
// Gets the URL from the UI's text field.
       
String stringUrl = urlText.getText().toString();
       
ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService
(Context.CONNECTIVITY_SERVICE);
       
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
       
if (networkInfo != null && networkInfo.isConnected()) {
           
new DownloadWebpageText().execute(stringUrl);
       
} else {
            textView
.setText("No network connection available.");
       
}
   
} /* Here we take thread to down load image etc

     
private class DownloadWebpageText extends AsyncTask {
       
@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);
       
}
   
}
}
Now we almost complete our task. Just we need to create a function that will handle download from url. So here is the final function


/* we pass the url from asynchronous task */

private String downloadUrl(String myurl) throws IOException {
   
InputStream is = null;
 
  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(DEBUG_TAG, "The response is: " + response);
       
is = conn.getInputStream();

       
// Convert the InputStream into a string See this Link
       
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();
       
}
   
}
}

So its done. Now you have string response you can do anything what your requirement tell you to do. 

converting InputStream to string

We are very much aware about InputStream. InputStream is to  read to content from file or URL. If we handle file then we used FileInputStream and while reading from a URL, we used InputStream.


InputStream is a readable source of bytes. Once you get an InputStream it's common to decode or convert it into a target data type. For example, if you were downloading image data, you might decode and display it directly Read this post to know how to convert input stream to bitmap See How to convert InputStream to bitmap. But if we want to convert InputStream to string then we need to read it line by line like given code


// Reads an InputStream and converts it to a String.
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}


Posting Lama ►
 

Copyright 2013 Tutorials For Newbie: Network Template by CB Blogger Template. Powered by Blogger