I have an Observer Design pattern that uses a Thread to send my own Events
. Sometimes the classes that are called are Android Activities and other times they are regular classes. The code in the Thread is NOT an Activity.
I was getting this error:
Can't create handler inside thread that has not called Looper.prepare()
To avoid that run-time error I had to add Looper.prepare()
inside the Thread. I am aware of this post: Can't create handler inside thread that has not called Looper.prepare() it contains the best information for this kind of problem, but still I don't know how to integrate the answer by mjosh into my Thread.
Problem
The call from the Thread to the Activity never happens. In isolation this code works, but not when Activities are waiting for the call.
This class will send Events to other classes. This one runs with a Thread.
public class EventBus
{
// Non essential code here.
...
// Thread code.
private class MyThread implements Runnable
{
@Override
public void run()
{
while(true)
{
synchronized(list)
{
for(Observer o : list)
// Execution transfers to Activity here.
o.handleEvent(event);
}
}
}
}
}
Inside an Activity.
public class FirstActivity extends Activity implements Observer
{
public void handleEvent()
{
// Never gets here.
}
}
So how do I solve this problem? My whole app will have many Activities and many regular classes.
To Solve my Problem
I need a way to keep my Thread alive and making calls to Activities. This might be a mixture of adding some code to the Thread so that it can successfully send my calls to the Activities.