tags:

views:

135

answers:

2

Is there a robust way to detect if Thread.currentThread() is the Android system GUI-thread in an application? I would like to put some asserts in my model code that asserts that only one thread (eg the gui-thread) accesses my state, to assure that no kind of synchronization is neccesary.

A: 

Couldn't you use the runOnUiThread method in the Activity class?

http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29

Roflcoptr
My application is working, but, it has several authors and is becomming rather big and complex. What I want to do is to add an extra safety net, an assert that catches the misstake if somebody is calling a method that is designed to only be called from the GUI-thread from another thread.
ParDroid
A: 

You could use Thread.toString(). It returns a string which can be used to uniquely identify each thread. Use it to compare your main gui's thread. Get the main GUI thread from OnCreate with a call like this: Thread.currentThread().toString()

Brad Hein
Don't use the name, several threads can have the same name. You should rely on the thread's identity instead. Just keep a reference to the Thread.
Romain Guy
Interesting, thanks for pointing that out Romain. Can you suggest an example where two threads may have the same .toString()?
Brad Hein
Thanks Romain for the idea of retaining a reference to the thread. I guess I can make a static MyAsserter.assertAlwaysSameThread() that keeps a thread reference and checks that its always the same thread that calls it. And also make sure to call it in onCreate aswell.
ParDroid