I saw most of the related questions, but I couldn\'t find any that fixed my problem.
This is my code, and I have no idea what I\'m doing wrong.
stati
A Handler
is basically a callback class that Android uses to asynchronously run code when you send it messages of some form. In order for a Handler
to receive and handle messages in a separate thread from the UI thread, it must keep the thread open. That is where the Looper class comes in. Like in the example of the page, call Looper.prepare()
at the top of the run()
method, then call Looper.loop()
at the bottom. The thread will stay open until you explicitly destroy it. In order to destroy a Looper
thread, you must have a method in your Thread
class that calls Looper.getMyLooper().quit()
.
An example thread class would be something like this:
class LooperThread extends Thread {
public Handler mHandler;
private volatile Looper mMyLooper;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
mMyLooper = Looper.getMyLooper();
Looper.loop();
}
public void killMe(){
mMyLooper.quit();
}
}
Run the thread normally by creating a new object of it.
LooperThread myLooperThread = new LooperThread();
Hold a reference to it. Then call:
myLooperThread.killMe();
Whenever you want the thread to die. This is usually in the onPause()
, onStop()
, or onDestroy()
methods of the Activity.
Please note that a thread of this nature will stay open when the activity is closed so you must kill it before the user quits.
I recommend using HandlerThread as it prepares the looper for you.
http://developer.android.com/reference/android/os/HandlerThread.html
Runs the specified action on the UI thread
ActivityName.runOnUiThread(new Runnable() {
public void run()
{
//put your logic here
}
});