我正在开发一个Android项目,我遇到了问题。
如果我实现以下代码,它可以正常工作。
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();
我实际上要做的是创建一个实现runnable的类,但是当我尝试启动它时,我会得到NetworkOnMainThreadException
的异常。
以下是我的课程
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;
}
}
以下是我尝试启动帖子的方法
AddServerThread addServerThread = new AddServerThread();
addServerThread.run();
我知道这个异常意味着什么,我不明白为什么它适用于第一种方法,但是当我使用实现Runnable I的类时,然后得到异常。
感谢您提供的任何帮助
答案 0 :(得分:0)
在runnable上调用run不会启动新线程。您需要将其作为参数传递给线程。
Thread thread = new Thread(yourRunnable); thread.start();