以下选项显示错误
Android应用程序+多播+绑定+单元格数据关闭
如果我连接到wifi router
,则不会发生错误。我有什么不对或 android + multicast + tethering impossible ?
public class Multicast {
final static String INET_ADDR = "224.0.0.1";
final static int PORT = 8888;
private Context mContext;
public Multicast(Context context) {
mContext = context;
}
public static NetworkInterface getWlanEth() {
final String TAG = "NetworkInterface";
Enumeration<NetworkInterface> enumeration = null;
try {
enumeration = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
NetworkInterface wlan0 = null;
StringBuilder sb = new StringBuilder();
while (enumeration.hasMoreElements()) {
wlan0 = enumeration.nextElement();
sb.append(wlan0.getName() + " ");
if (wlan0.getName().equals("wlan0")) {
return wlan0;
}
}
return null;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
public void startMulticastServer() {
Thread sendThread = new Thread(new Runnable() {
DatagramSocket serverSocket;
@Override
public void run() {
try {
if (serverSocket == null) {
serverSocket = new DatagramSocket(null);
serverSocket.setReuseAddress(true);
serverSocket.setBroadcast(true);
serverSocket.bind(new InetSocketAddress(PORT));
serverSocket.setSoTimeout(15000);
}
for (int i = 0; i < 5; i++) {
String msg = "Sent message no " + i;
InetAddress group = InetAddress.getByName(INET_ADDR);
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, group, PORT);
serverSocket.send(msgPacket);
String TAG = "Multicast-send";
Log.i(TAG, "Socket 1 send msg: " + msg);
Thread.sleep(500);
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
sendThread.start();
}
public void startMulticastClient() {
Thread getThread = new Thread(new Runnable() {
byte[] buf = new byte[256];
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void run() {
//Acquire the MulticastLock
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifi.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
// Create a new Multicast socket (that will allow other sockets/programs
// to join it as well.
try {
MulticastSocket clientSocket = new MulticastSocket(PORT);
//Joint the Multicast group.
clientSocket.joinGroup(new InetSocketAddress(InetAddress.getByName(INET_ADDR), PORT), getWlanEth());
clientSocket.setLoopbackMode(true);
while (true) {
// Receive the information and print it.
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket);
String msg = new String(msgPacket.getData());
String TAG = "Multicast-get";
Log.i(TAG, "Socket 1 received msg: " +msgPacket.getAddress()+" : "+ InetAddress.getByName(INET_ADDR) + " : " +msg);
}
} catch (IOException ex) {
multicastLock.release();
ex.printStackTrace();
}
multicastLock.release();
}
});
getThread.start();
}
}