Created
June 25, 2016 21:44
-
-
Save kaushikgopal/19268bef99a644aea4728de7c2ebb3bf to your computer and use it in GitHub Desktop.
Blog post snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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