Showing posts with label Background Work. Show all posts
Showing posts with label Background Work. 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. 

Sunday, April 15, 2012

Asynchronous task, Updating UI from background in android

As all we know in android there are two ways to perform background task such as downloading image and other task that include long operation
  • Using Thread 
  • Asynchronous Task                          
Using Thread, there is one dis-advantage that we can not update user interface other wise we will get Looper.loop() exception

So its efficient to use Asynchronous task.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.


Let take one example of downloading images from URL's Array.So body of Asynchronous task 's body will be like this
 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     
protected Long doInBackground(URL... urls) {
         
int count = urls.length;
         
long totalSize = 0;
         
for (int i = 0; i < count; i++) {
             totalSize
+= Downloader.downloadFile(urls[i]);
             publishProgress
((int) ((i / (float) count) * 100));
         
}
         
return totalSize;
     
}

     
protected void onProgressUpdate(Integer... progress) {
         setProgressPercent
(progress[0]);
     
}

     
protected void onPostExecute(Long result) {
         showDialog
("Downloaded " + result + " bytes");
     
}
 
}
 
    Like Thread we can create asynchronous task like this
 new DownloadFilesTask().execute(url1, url2, url3);
    Now asynchronous has three generic type.Let have a look on their requirement 
    



  • Params, the type of the parameters sent to the task upon execution.
  • Progress, the type of the progress units published during the background computation.
  • Result, the type of the result of the background computation.

  •     
    But its not necessary to use all type.you can set like this if you do not want to use 
    private class MyTask extends AsyncTask<Void, Void, Void> { ... }
     Now it has four step -
    1)  onPreexecute() -Before it start executing it call this method .It call before it goes to perform task in background so we can display a ProgressDialog here )doInBackground() - perform long background task here

    3)onProgressUpdate() - Update your progress of dialog to show to user

    4)onPostExecute() - Post or show your result here .Dismiss progress dialog  box here
    There are a few threading rules that must be followed for this class to work properly: