Checking whether the current thread is the UI/Main thread or some other background thread is very easy. Here’s the code for it:
if (Looper.myLooper() == Looper.getMainLooper()) { // Current thread is the UI/Main thread } // Another approach if (Looper.getMainLooper().getThread() == Thread.currentThread()) { // Current thread is the UI/Main thread }
Bonus: If you’re in a thread other than the UI Thread and you want to execute a piece of code in the UI thread then you can make use of the runOnUiThread()
method.
What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.
// Sample code from one of my Android applications runOnUiThread(new Runnable(){ public void run() { mChatMessages.clear(); mChatMessages.addAll(chatMessages); mChatLogAdapter.notifyDataSetChanged(); } });
Hope that helps!
Recommended for you: Get network issues from WhatsUp Gold. Not end users.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download