Click here to Skip to main content
15,882,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to receive udp packets being sent from another android machine.II can receive the same packets over java udp client program however same not working on android. here is my code:

Java
//Main Activity

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.v("Main Activity", "intialized started");
    list = (ListView) findViewById(R.id.listview1);

    mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiReciever = new WifiScanReceiver();
    mainWifiObj.startScan();
    Log.v("Main Activity", "MainActivity started");

    clientDatagramReceiver=new ClientDatagramReceiver();
    clientDatagramReceiver.start();


Java
//clientdatagramreceiver class

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import android.util.Log;
import android.widget.Toast;

public  class ClientDatagramReceiver extends Thread {
    private DatagramSocket datagramsocket = null;
    private boolean bKeepRunning = true;
    InetAddress serverIP=null;

    public ClientDatagramReceiver() {
        try {
            datagramsocket = new DatagramSocket(7999);
            Log.v("ClientDatagramSender", "Socket Created");
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.v("ClientDatagramSender", "Socket Unicast SET");
        }
    }

    public void run() {
        byte[] messageBytes = new byte[10];

        DatagramPacket packet = null;
        while(this.bKeepRunning) {
            packet = new DatagramPacket(messageBytes, 10);
            Log.d("ClientDatagramReceiver", "RECEIVING PACKET CREATED");
            try {
                datagramsocket.receive(packet);
                Log.d("ClientDatagramReceiver", "INCOMING PACKET RECEIVED");
            } catch (IOException e) {
                e.printStackTrace();
            }
            serverIP=packet.getAddress();
            Log.d("ClientDatagramReceiver", "IP ADDRESS of REMOTE SENDER: " + serverIP.getHostAddress());

            ServerIpHelper.setServerIP(serverIP);

            ClientDatagramSender.killAllThreads();
            Log.d("ClientDatagramReceiver", "STOPPING BROADCAST SERVICE");

            this.bKeepRunning = false;
            Log.d("ClientDatagramReceiver", "RECEIVER CLOSED");
        }
    }
}
Posted
Updated 19-Nov-14 2:50am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900