Android's UDP programming instance _android

Source: Internet
Author: User
One, some mobile phone can not directly receive UDP packets, may be the handset manufacturers in the custom ROM when the function to turn off.
1, can first in the OnCreate () method inside the instantiation of a Wifimanager.multicastlock object lock, as follows:
Copy Code code 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 to send or receive messages;
3, after the use of timely call Lock.release () release resources, veto multiple calls Lock.acquire () method, the program may collapse, please see the details
caused by:java.lang.UnsupportedOperationException:Exceeded maximum number of WiFi locks
Note: Remember to add the following permissions to the configuration file.
Copy Code code as follows:

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

After such treatment, most mobile phones can send and receive broadcast messages normally.
This dot is reproduced from the Android phone does not receive UDP messages
second, in the UDP communication, the Android side to send UDP broadcast packets no problem. As for receiving, it is sometimes not possible to receive packets.
There is no problem with the Android side sending UDP broadcast packets in UDP traffic. As for receiving, it is sometimes not possible to receive packets. However, if the target host's address is specified in the UDP packet, the Android side will receive it properly.
The following section of the code, you can use this code to test.
1, in a service, we create a thread
Copy Code code as follows:

public void OnCreate () {//for creating threads
Wifimanager manager = (Wifimanager) This
. Getsystemservice (Context.wifi_service);
Udphelper = new Udphelper (manager);

Pass the Wifimanager object to use in the Udphelper class Multicastlock
Udphelper.addobserver (Msgreceiveservice.this);
treceived = new Thread (udphelper);
Treceived.start ();
Super.oncreate ();
}

2, get a UDP help class, this class is mainly used to send and receive data
Copy Code code as follows:

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 Help Class
*
* @author Chen
*
*/
public class Udphelper implements Runnable {
Public Boolean isthreaddisable = false;//Indicates whether the listener thread is terminated
private static Wifimanager.multicastlock lock;
InetAddress minetaddress;
Public Udphelper (Wifimanager manager) {
this.lock= Manager.createmulticastlock ("Udpwifi");
}
public void Startlisten () {
Ports that the UDP server listens on
Integer port = 8903;
The size of the bytes received, the data sent by the client cannot exceed this size
byte[] message = new BYTE[100];
try {
Establish a socket connection
Datagramsocket datagramsocket = new Datagramsocket (port);
Datagramsocket.setbroadcast (TRUE);
Datagrampacket datagrampacket = new Datagrampacket (message,
Message.length);
try {
while (! isthreaddisable) {
Preparing 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 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 ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.