1

我正在尝试向服务器发送一个 UDP 数据包以查看它是否在线。我已经制作了一个独立的应用程序来做到这一点,它可以毫无问题地工作,但是当将代码放入应用程序并调用函数时,它会在实际发送数据包时引发异常。我做了很多研究,我找不到任何原因。我用假IP替换了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”

4

1 回答 1

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();

参考 :

无痛穿线

于 2013-01-21T23:59:00.803 回答