I am trying 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