Search code examples
androidudpsendping

Android throws exception when sending UDP packet


I'm trying to send a UDP packet to a server to see if it is online. I have made a stand alone app to do exactly that and it works without a problem but when putting the code in the app and calling the function it throws an exception when it goes to actually send the packet. I have done a lot of research and I can't find any reason why. I replaced the IP with a fake one because I don't want to post the actual IP. Thanks for the help in advanced.

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;
    }
}

}

When printing the exception i got "android.os.NetworkOnMainThreadException"


Solution

  • Declare this asyncTask in the activity and call your check() method from there.

    EDIT:

    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.
        }       
    }
    

    And make this call :

    new CheckStatusTask().execute();
    

    Reference :

    Painless threading