Forcing class methods to be called from ui thread

92 views Asked by At

I created a class and I want it's methods to be available to call only from one specific thread, for instance, the ui-thread. It's exactly the opposite from what happens in the android networking api... it throws an exception when it is called from the ui-thread. How can I do that in android? thanx

3

There are 3 answers

0
egur On

This behavior is how MFC works:

An MFC Window class has many methods that DO NOT perform what is expected from them, instead they send or post a message to a queue that the GUI/main thread listens on.

So you need to either use an existing cross thread messaging mechanism or create your own.

1
Abhishek Shukla On

Well, you can do it even inside your class. Just, get the context of caller activity. And in the method, do context.runOnUIThread()

0
Vishal Vijay On

Put this code inside your class methods.

   if(!"UI thread".equals(Thread.currentThread().getName())){
    throw new IllegalStateException("wrong thread running this class, thread name:"+Thread.currentThread().getName());
    }