I am working on an Android project and I am having a problem.
If I implement the below code, it works fine.
new Thread(new Runnable() {
@Override
public void run() {
try
{
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
DatagramSocket datagramSocket = new DatagramSocket(8000);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true)
{
datagramSocket.receive(packet);
Log.v(TAG, new String(packet.getData(), 0, packet.getLength()));
}
}
catch (SocketException ex)
{
Log.e(TAG, "Failed to bind socket. Exception: " + ex.toString());
}
catch (IOException ex)
{
Log.e(TAG, "Failed to read socket data. Exception: "+ ex.toString());
}
}
}).start();
What I am actually trying to do is create a class that implements a runnable but when I attempt to start it, I then get the exception for NetworkOnMainThreadException
.
Below is my class
public class AddServerThread implements Runnable {
private static final String TAG = "ADD SERVER THREAD";
private boolean cancelThread = false;
@Override
public void run()
{
Log.d(TAG, "Listening for available servers");
try
{
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
DatagramSocket datagramSocket = new DatagramSocket(8000);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (!cancelThread)
{
datagramSocket.receive(packet);
Log.v(TAG, new String(packet.getData(), 0, packet.getLength()));
}
}
catch (SocketException ex)
{
Log.e(TAG, "Failed to bind socket. Exception: " + ex.toString());
}
catch (IOException ex)
{
Log.e(TAG, "Failed to read socket data. Exception: "+ ex.toString());
}
}
public void cancelThread()
{
cancelThread = true;
}
}
Below is how I am trying to start the thread
AddServerThread addServerThread = new AddServerThread();
addServerThread.run();
I know what this exception means, what I don't understand is why it works on the first method, but when I use the class implementing Runnable I then get the exception.
Thanks for any help you can provide