http://blog.csdn.net/ghostyu/article/details/8182516

Android的Wifi,默认情况下是不接受组播的,见:http://developer.android.com/reference/android/net/wifi/WifiManager.MulticastLock.html

默认情况下,应用是不接收组播信息的,这样要接收处理的报文太多,很快就会把电池用尽。要知道移动设备(特指电话一类的,平板要好得多)目前最重要的因素是电量。

要想打开组播功能,有以下几个步骤:

  • 在Manifest文件中加入:android.permission.CHANGE_WIFI_MULTICAST_STATE,这个权限
  • 获取到MulticastLock对象,这个对象不能直接实例化,要通过WifiManager间接得到,工厂模式
  • 调用MulticastLock对象的acquire方法,获取到组播锁
  • 相应的,用完组播,为了不浪费电力,要调用MulticastLock的release方法释放锁

1、创建组播用的udp socket,

2、绑定组播地址为239.255.255.250,端口为3702,因为ws-discovery的组播地址和端口就是为239.255.255.250和3702

直接上代码:

public class MulticastDemoActivity extends Activity {             MulticastLock multicastLock;             /** Called when the activity is first created. */       @Override       public void onCreate(Bundle savedInstanceState) {           super.onCreate(savedInstanceState);           setContentView(R.layout.main);                     allowMulticast();                     try {               NetUtil.findServerIpAddress();           } catch (IOException e) {               throw new RuntimeException(e);           }                     Log.d("multicast.demo", "find ip ok.");                     multicastLock.release();       }             private void allowMulticast(){           WifiManager wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);           multicastLock=wifiManager.createMulticastLock("multicast.test");           multicastLock.acquire();       }   }

public class NetUtil {             private static final String TAG="Net.Utils";       private static final int MULTICAST_PORT=5111;       private static final String GROUP_IP="224.5.0.7";       private static byte[] sendData;             static{           sendData=new byte[4];           // 0xEE78F1FB           sendData[3] = (byte) 0xEE;           sendData[2] = (byte) 0×78;           sendData[1] = (byte) 0xF1;           sendData[0] = (byte) 0xFB;       }             public static String findServerIpAddress() throws IOException{           String ip=null;            MulticastSocket multicastSocket=new MulticastSocket(MULTICAST_PORT);           multicastSocket.setLoopbackMode(true);           InetAddress group = InetAddress.getByName(GROUP_IP);           multicastSocket.joinGroup(group);                     DatagramPacket packet=new DatagramPacket(sendData, sendData.length,group,MULTICAST_PORT);                     for(;;){               multicastSocket.send(packet);               Log.d(TAG,">>>send packet ok");                             byte[] receiveData=new byte[256];               packet=new DatagramPacket(receiveData, receiveData.length);               multicastSocket.receive(packet);                             String packetIpAddress=packet.getAddress().toString();               packetIpAddress=packetIpAddress.substring(1, packetIpAddress.length());               Log.d(TAG,"packet ip address: "+packetIpAddress);                             StringBuilder packetContent=new StringBuilder();               for(int i=0;i<receiveData.length;i++){                   if(receiveData[i]==0){                       break;                   }                   packetContent.append((char)receiveData[i]);               }               ip=packetContent.toString();               Log.d(TAG,"packet content ip is: "+ip);                             if(ip.equals(packetIpAddress)){                   Log.d(TAG,"find server ip address: "+ip);                   break;               }else{                   Log.d(TAG,"not find server ip address, continue …");                   try {                       Thread.sleep(1000);                   } catch (InterruptedException e) {                   }               }           }                     return ip;       }   }  

上面代码供参考,但是没有测试在htc手机上成功

下面是本人修改过的代码:

public static String findServerIpAddress() throws IOException {                String sinfo = "";        byte[] sendData = sinfo.getBytes();        String ip = "";        try {            MulticastSocket multicastSocket = new MulticastSocket(                    MULTICAST_PORT);            multicastSocket.setLoopbackMode(true);//修改添加代码部分不添加不能发送成功            InetAddress group = InetAddress.getByName(GROUP_IP);            multicastSocket.setLoopbackMode(true);            multicastSocket.joinGroup(group);            multicastSocket.setSoTimeout(10000);            DatagramPacket packet = new DatagramPacket(sendData,                    sendData.length, group, MULTICAST_PORT);            for (;;) {                multicastSocket.send(packet);                Log.d(TAG, ">>>send packet ok");                byte[] receiveData = new byte[256];                packet = new DatagramPacket(receiveData, receiveData.length);                multicastSocket.receive(packet);                String packetIpAddress = packet.getAddress().toString();                packetIpAddress = packetIpAddress.substring(1,                        packetIpAddress.length());                Log.d(TAG, "packet ip address: " + packetIpAddress);                StringBuilder packetContent = new StringBuilder();                for (int i = 0; i < receiveData.length; i++) {                    if (receiveData[i] == 0) {                        break;                    }                    packetContent.append((char) receiveData[i]);                }                ip = packetContent.toString();                Log.d(TAG, "packet content ip is: " + ip);                if (ip.equals(packetIpAddress)) {                    Log.d(TAG, "find server ip address: " + ip);                    break;                } else {                    Log.d(TAG, "not find server ip address, continue …");                    try {                        Thread.sleep(1000);                    } catch (InterruptedException e) {                    }                }            }        } catch (Exception ee) {            Log.d(TAG, ee.toString());        }        return ip;    }

http://blog.csdn.net/lvron/article/details/6606755

更多相关文章

  1. 如何通过代码更改ANDROID的UI布局
  2. Android(安卓)UI开发第二篇——多级列表(ExpandableListView)
  3. Android(安卓)编程设置 APN
  4. windows下载android源代码
  5. 2010.11.28(2)———android 展示网页 和 调用js代码
  6. windows下载android源代码
  7. android jni 程序框架搭建
  8. Android(安卓)SDK中国在线更新镜像服务器 解决GOOGLE更新无法下
  9. Android(安卓)View添加 Listener 小技巧示例

随机推荐

  1. Android初学笔记——五:数据存储
  2. 2.2 android中的多进程机制
  3. Android(安卓)显示手机电池的当前电量
  4. android分区大小的修改说明(RK)
  5. android 动态设置margin
  6. Android(安卓)代码规范 code style
  7. android 2.2(froyo)源码下载
  8. android 学习笔记(一):2 模拟器的使用
  9. [Linphone Android] 登录实现
  10. android软银盘始终显示,并显示在焦点上