Monday, May 28, 2012

Android: Running Background Tasks

In my app I'm using the asmack library as the back bone for packet sending and processing. Doing these in the context of the UI thread is not ideal as it may freeze the UI and leads to perception of app freezing. 


The better way to solve this problem is to run these tasks in the background. In general, this can be solved by having the UI thread queueing a Runnable onto an executor, and having the Runnable send a Broadcast when it finishes.


In practice, you'll need to instantiate an executor first: 

       /**
* Restart the executor pool.

*/
private void initExecutor() {


m_executor = Executors.newFixedThreadPool(1);
}



Then implement your Runnable:

/**
* Logs into the server.

*/
private class loginRunnable implements Runnable {


String user;
String pass;


public loginRunnable(String user, String pass) {


m_loginUser = user;
this.user = user;
this.pass = pass;
}


public void run() {


// TODO: 
                        // Implement your login routine. 


// Notify login success.
m_app.sendBroadcast(new Intent(LOGIN_SUCCESS));
}
}


To queue the login request, simply do: 
        m_executor.execute(new loginRunnable(user, pass));


After your Activity queues the Runnable onto the Executor, you should consider populating a loading Dialog indicate the request is being processed. The Dialog should be cancelled when the complete event is received in the Broadcast Receiver. 

No comments:

Post a Comment