Android: Issue using a handler and postDelayed()
I am tryi开发者_JAVA百科ng to use a Handler to have some code execute in some amount of time.
This works well in 2 of my classes, but I'm running on an issue with this one:
One of my class extends Activity, and starts a Thread (that implements Runnable).
In my run() method, I have, as in my other classes:
mHandler = new Handler();
mHandler.removeCallbacks(StopRequest);
mHandler.postDelayed(StopRequest, 30000);
The program seems to complain:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I don't understand why it is posting, could someone please help me?
EDIT: Adding parts of my code:
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(clientSocket.getOutputStream())), true);
out.println("VOICE_CALL_REQUEST");
// Wait for a response
// Set a timer (about 30 seconds)
mHandler = new Handler();
mHandler.removeCallbacks(StopRequest);
mHandler.postDelayed(StopRequest, 3000);
// Ready reply
InputStream stream = clientSocket.getInputStream();
BufferedReader data = new BufferedReader(new InputStreamReader(stream));
String line = data.readLine();
mHandler.removeCallbacks(StopRequest); // Timer is removed here
And if the timer hits 30 seconds:
// Stop a call request after some amount of time
private Runnable StopRequest = new Runnable() {
public void run() {
// Send a message to cancel the voice call
out.println("VOICE_CALL_CANCEL");
// Close the port
try {
clientSocket.close();
}
catch (IOException e) { finish(); }
}
};
Thanks a lot,
Jary
You can't create a handler in a worker thread (unless it has a looper, which you normally never do). The handler needs a looper, since it needs a point that evaluates all incoming messages and calls the handler when necessary.
Your handler needs to be in the UI thread. If you want to do something in a worker thread, you need to do your own message handling (you could use synchronized methods in your thread that set member variables which the worker thread checks), or, if your thread is more of the event-driven variety, you could really consider adding a looper - but again, that is not a common practice.
I found a solution. Defining the handler in the onCreate method fixes it. Rest of the code is identical. Thanks :)
精彩评论