public class LooperThread extends Thread {
private Handler handler = null;
public Handler getHandler() {
return handler;
}
@Override
public void run() {
Looper.prepare();
handler = new Handler();
Looper.loop();
}
}
class Helper {
private static LooperThread databaseThread = null;
static {
databaseThread = new LooperThread();
databaseThread.start();
}
public void postRunable(Runnable r) {
databaseThread.getHandler().post(r);
databaseThread.getHandler().sendMessage(new Message());
}
}
//ui thread.
class UIActivity extends Activity {
private Helper helper = new Helper();
public void onCreate(Bundle savedInstanceState) {
helper.postRunnable(new Runnable() {
public void run() {
//work asyn,like query from db.
}
});
}
}
sometimes call databaseThread.getHandler().post(r);
,it return null,sometime are not,why this?as usual,handler
should be initial by static block.
You are some times getting a null Handler
because calling databaseThread.start();
in the the static initializer only ensures that the thread will be started at some point in the future this means thats creating a race condition between the handler getting created inside the new thread and getHandler()
being called in the old one. Having a thread with a background looper is a very common pattern in Android so there is a class to help us with this.
First get rid of your LooperThread
class and use the SDK's HandlerThread
instead.
Your Helper
class should now look like
class Helper {
private static final HandlerThread databaseThread;
private static final Handler dbHandler;
static {
databaseThread = new HandlerThread("database thread");
databaseThread.start();
// If you have called HandelerThread#start()
// HandlerThread#getLooper() will block until the looper is initialized and Looping
dbHandler = new Handler(databaseThread.getLooper());
}
public void postRunable(Runnable r) {
dbHandler.post(r);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With