Created
March 19, 2018 19:41
-
-
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
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
//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