rablentain
rablentain

Reputation: 6745

Why does my UDP message from Android not work?

I have written a small java code script that sends a message via UDP to a server on my computer:

@Override
public void onClick(View view) {
    try {
        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IP = InetAddress.getByName("192.168.1.5");
        byte[] sendData = new byte[1024];
        String sentence = "HELLO";

        sendData = sentence.getBytes();

        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IP, 9876);
        clientSocket.send(sendPacket);

        clientSocket.close();
    } catch(IOException e) {

    }
}

I have tried the same code from another computer on the network, and the message is then correctly sent and received. When I am trying to run this from my Android phone, the server wont receive it. Why is that?

EDIT

I had forgot to add internet permisson in the manifest, but when I did that, the app crashes when I click the button:

06-13 21:14:26.932  13501-13501/com.example.omgandroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1144)
        at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
        at libcore.io.IoBridge.sendto(IoBridge.java:466)
        at java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182)
        at java.net.DatagramSocket.send(DatagramSocket.java:284)
        at com.example.omgandroid.MainActivity.onClick(MainActivity.java:72)
        at android.view.View.performClick(View.java:4475)
        at android.view.View$PerformClick.run(View.java:18786)
        at android.os.Handler.handleCallback(Handler.java:730)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:5419)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
        at dalvik.system.NativeStart.main(Native Method)
06-13 21:14:38.987  13501-13501/com.example.omgandroid I/Process﹕ Sending signal. PID: 13501 SIG: 9

What could be the cause of this?

Upvotes: 1

Views: 1128

Answers (1)

mike_m
mike_m

Reputation: 1546

Android doesn't allow network connections from the main thread (NetworkOnMainThreadException), to not block the user interface. They want the user interface to be responsive and not blocked by network operations, so the user won't think that the app crashed.

You have to do the network stuff inside a new thread.

AsyncTask is good for that.

Upvotes: 2

Related Questions