Saturday, October 13, 2012

Background threads in Android.

Frequently, in Android, you need your application to actually "do" something.  Hey, it's an application, it's to be expected.  In Android, best practice dictates you don't use the main UI thread to do this. It makes your application non-responsive until the task completes.  In fact, a default Android Project won't even allow you to run things on the main thread. 

This is where your friendly ASyncTask comes in.   

This task below, takes an integer as input, and then the background thread then returns a string, the void method is where you can update your UI etc for the result, the string that is considered input for that method, is in fact the same string returned in the "doInBackground" method.

This code can be customized to take in whatever initial variable type, and whatever end variable type. (I.E. Modify "Integer" to "String")

private class task extends AsyncTask<Integer, Void, String> {

private Exception exception;

protected String doInBackground(Integer... arg0) 
   StringBuilder builder = new StringBuilder();
   return builder.toString();
protected void onPostExecute(String feed) throws NullPointerException 


No comments:

Post a Comment