Android的Wifi,默認狀況下是不接受組播的,見:http://developer.android.com/reference/android/net/wifi/WifiManager.MulticastLock.htmlhtml
默認狀況下,應用是不接收組播信息的,這樣要接收處理的報文太多,很快就會把電池用盡。要知道移動設備(特指電話一類的,平板要好得多)目前最重要的因素是電量。android
要想打開組播功能,有如下幾個步驟:服務器
下面寫了個簡單示例,經過組播發現服務器。app
Activity寫的比較簡單:ide
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();
}
}工具
在Activity中打開和釋放組播鎖。oop
使用組播發送報文和接收ip地址信息的工具類代碼:ui
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;serverMulticastSocket 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;
}
}htm