An UDP programming instance of android

  • 2020-05-19 05:46:47
  • OfStack

1. Some phones cannot receive the UDP package directly, maybe the phone manufacturer turned off this function when customizing Rom.
1. You can first instantiate an WifiManager.MulticastLock object lock in the oncreate() method; The details are as follows:

WifiManager manager = (WifiManager) this
                .getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock lock= manager.createMulticastLock("test wifi");

2. Call the lock.acquire () method before calling the broadcast sending and receiving message;
3. Timely call lock.release () to release the resource after using it, and veto multiple calls to lock.acquire (). The program may crash, please see details
Caused by: java.lang.UnsupportedOperationException: Exceeded maximum number of wifi locks
Note; Remember to add the following permissions to the profile:

<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

After such processing, most mobile phones can normally send and receive broadcast messages.
This dot is reprinted from Android mobile phone and cannot receive UDP message
2. In UDP communication, there is no problem for the android end to send UDP broadcast packets. As for receiving, sometimes you can't receive a packet.
In UDP communication, the android end has no problem sending UDP broadcast packets. As for receiving, sometimes you can't receive a packet. However, if the address of the target host is specified in the UDP package, the android end will receive it normally.
Here is the code that you can test.
1. In an Service, we create a thread

public void onCreate() {// For creating threads 
        WifiManager manager = (WifiManager) this
                .getSystemService(Context.WIFI_SERVICE);
        udphelper = new UdpHelper(manager);

        // pass WifiManager Object in order to UDPHelper Class to use MulticastLock
        udphelper.addObserver(MsgReceiveService.this);
        tReceived = new Thread(udphelper);
        tReceived.start();
        super.onCreate();
    }

2. Create an UDP help class, which is mainly used to send and receive data

package com.example.com.ihome.bang.util;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Observable;
import com.example.com.ihome.bang.tool.SendThread;
import android.net.wifi.WifiManager;
import android.util.Log;
/**
 * 
 * UdpHelper Helper classes 
 * 
 * @author  Chen � rongping 
 * 
 */
public class UdpHelper  implements Runnable {
    public    Boolean IsThreadDisable = false;// Indicates whether the listening thread terminates 
    private static WifiManager.MulticastLock lock;
    InetAddress mInetAddress;
    public UdpHelper(WifiManager manager) {
         this.lock= manager.createMulticastLock("UDPwifi"); 
    }
    public void StartListen()  {
        // UDP The port on which the server is listening 
        Integer port = 8903;
        //  The size of the bytes received and the data sent by the client cannot exceed this size 
        byte[] message = new byte[100];
        try {
            //  To establish Socket The connection 
            DatagramSocket datagramSocket = new DatagramSocket(port);
            datagramSocket.setBroadcast(true);
            DatagramPacket datagramPacket = new DatagramPacket(message,
                    message.length);
            try {
                while (!IsThreadDisable) {
                    //  Ready to receive data 
                    Log.d("UDP Demo", " Ready to accept ");
                     this.lock.acquire();

                    datagramSocket.receive(datagramPacket);
                    String strMsg=new String(datagramPacket.getData()).trim();
                    Log.d("UDP Demo", datagramPacket.getAddress()
                            .getHostAddress().toString()
                            + ":" +strMsg );this.lock.release();
                }
            } catch (IOException e) {//IOException
                e.printStackTrace();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    public static void send(String message) {
        message = (message == null ? "Hello IdeasAndroid!" : message);
        int server_port = 8904;
        Log.d("UDP Demo", "UDP To send data :"+message);
        DatagramSocket s = null;
        try {
            s = new DatagramSocket();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress local = null;
        try {
            local = InetAddress.getByName("255.255.255.255");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        int msg_length = message.length();
        byte[] messageByte = message.getBytes();
        DatagramPacket p = new DatagramPacket(messageByte, msg_length, local,
                server_port);
        try {
            s.send(p);
            s.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
            StartListen();
    }
}

Related articles: