Skip to content

Instantly share code, notes, and snippets.

@eSpecialized
Created March 19, 2018 19:41
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 eSpecialized/e217b776da43af880f63b0585c7065c0 to your computer and use it in GitHub Desktop.
Save eSpecialized/e217b776da43af880f63b0585c7065c0 to your computer and use it in GitHub Desktop.
Android Posting code to main thread using native java calls, aka handlers simplified with block calls posted to another thread
//You will want to create a Handler on the thread you wish to post code too.
// This makes Android development using code blocks far easier just like it can be on iOS.
public Handler mThreadHandler;
public void setupHandlerFromThreadMain() {
//Looper.prepare();
//if you are setting this up from the Main thread, then there is already a looper.
mThreadHandler = new Handler();
//Looper.loop();
}
public void createBackgroundThread() {
new Thread(new Runnable() {
@Override
public void run() { backgroundThread(); }
});
}
public void backgroundThread() {
//call back to the mThreadHandler
mThreadHandler.post(new Runnable() {
@Override
public void run() {
//block of code you want to run on another thread.
//calls to UI Functionality
mainThreadOnly();
}
});
}
public void mainThreadOnly() {
if (Looper.getMainLooper().getThread() != Thread.currentThread())
{
Log.e("MODULE", "Not running on main thread error!");
throw new IllegalThreadStateException("Needs to be on the main ui thread");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment