Skip to content

Instantly share code, notes, and snippets.

@kaushikgopal
Created June 25, 2016 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaushikgopal/19268bef99a644aea4728de7c2ebb3bf to your computer and use it in GitHub Desktop.
Save kaushikgopal/19268bef99a644aea4728de7c2ebb3bf to your computer and use it in GitHub Desktop.
Blog post snippet
public class TestActivity extends Activity {
// ...
// all standard stuff
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
// all standard stuff
// we're creating a new handler here
// and we're in the UI Thread (default)
// so this Handler is associated with the UI thread
Handler mHandler = new Handler();
// I want to start doing something really long
// which means I should run the fella in another thread.
// I do that by sending a message - in the form of another runnable object
// But first, I'm going to create a Runnable object or a message for this
Runnable mRunnableOnSeparateThread = new Runnable() {
@Override
public void run () {
// do some long operation
longOperation();
// After mRunnableOnSeparateThread is done with it's job,
// I need to tell the user that i'm done
// which means I need to send a message back to the UI thread
// who do we know that's associated with the UI thread?
mHandler.post(new Runnable(){
@Override
public void run(){
// do some UI related thing
// like update a progress bar or TextView
// ....
}
});
}
};
// Cool but I've not executed the mRunnableOnSeparateThread yet
// I've only defined the message to be sent
// When I execute it though, I want it to be in a different thread
// that was the whole point.
new Thread(mRunnableOnSeparateThread).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment