Checking whether the current thread is the UI/Main thread or some other background thread is very easy. Here’s the code for it:
[java]
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
}
[/java]
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.
[java]
// Sample code from one of my Android applications
runOnUiThread(new Runnable(){
public void run() {
mChatMessages.clear();
mChatMessages.addAll(chatMessages);
mChatLogAdapter.notifyDataSetChanged();
}
});
[/java]
Hope that helps!