我正在尝试将UDP数据包发送到服务器以查看它是否在线。我已经制作了一个独立的应用程序来完成它并且它没有问题但是当将代码放入应用程序并调用该函数时,它会在实际发送数据包时抛出异常。我做了很多研究,我找不到任何理由。我用假的替换了IP,因为我不想发布实际的IP。感谢先进的帮助。
import java.io.IOException;
import java.net.*;
import android.app.Activity;
public class CheckStatus extends Activity {
//Check if the server is online
public static boolean check() {
try {
byte[] receiveData = new byte[1024];
InetAddress address = InetAddress.getByName("11.11.11.11");
//create socket
DatagramSocket clientSocket = new DatagramSocket();
//set timeout
clientSocket.setSoTimeout(1000);
//send packet
DatagramPacket p = new DatagramPacket(Integer.toBinaryString(0x0006000000).getBytes(), 5, address, 44462);
clientSocket.send(p);//throws exception here
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
clientSocket.close();
return true;
} catch (Exception e) {
return false;
}
}
}
打印异常时我得到“android.os.NetworkOnMainThreadException”
答案 0 :(得分:2)
在asyncTask
中声明此activity
并从那里调用您的check()
方法。
修改强>
private class CheckStatusTask extends AsyncTask<Object, Object, Boolean> {
protected Boolean doInBackground(Object... arg0) {
boolean flag = check();
return flag;
}
protected void onPostExecute(Boolean flag) {
// use your flag here to check true/false.
}
}
拨打电话:
new CheckStatusTask().execute();
参考: