I am using a Thread
to start my ServerSocket
and I with transactions that take longer than 500ms.
I think that triggers some "App is not responding" messages.
I tried to create a thread that to separate it from the UiThread
.
Here is my code:
Thread socketServerThread=new Thread(new ServerSocketThread());
socketServerThread.start();
public class ServerSocketThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
@Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
Toast.makeText(getApplicationContext(), "server is on", Toast.LENGTH_SHORT).show();
while (true) {
Socket socket = serverSocket.accept();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My app crashes when I open it.
How can I solve those errors?
My LogCat:
04-11 21:57:23.864: E/AndroidRuntime(11761): FATAL EXCEPTION: Thread-11
04-11 21:57:23.864: E/AndroidRuntime(11761): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-11 21:57:23.864: E/AndroidRuntime(11761): at android.os.Handler.<init>(Handler.java:121)
04-11 21:57:23.864: E/AndroidRuntime(11761): at android.widget.Toast.<init>(Toast.java:68)
04-11 21:57:23.864: E/AndroidRuntime(11761): at android.widget.Toast.makeText(Toast.java:231)
04-11 21:57:23.864: E/AndroidRuntime(11761): at com.example.imagesender.MainActivity$ServerSocketThread.run(MainActivity.java:79)
04-11 21:57:23.864: E/AndroidRuntime(11761): at java.lang.Thread.run(Thread.java:1019)
the problem is you are trying to show a toast from a non UI thread which you cannot do, remove that and it should work.
If you want to show the toast then you have to use a handler to call back to the main thread or better yet use an AsyncTask