我最近尝试移植需要接收(udp)广播消息的应用程序。我的udp接收代码在pc(windows / linux)上运行,但是有了android似乎有一些接收广播消息的问题,但是,我似乎能够发送带有android的广播消息并从pc版本接收确认包。
试图找到解决方案但是接近答案的任何事情都是 MIGHT 无法在我的设备上运行,并且确实有任何关于我如何确定是这种情况的信息,所以觉得应该有线程,以确保它确实是硬件/固件问题,而不是我的代码中的问题,如果有特定的东西,我忘了启用?用galaxy S(kitkat)和Galaxy s3 mini(kitkat)测试,两者都有同样的问题
(在onCreate下)
WifiManager wifi;
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock wifilock = wifi.createMulticastLock("compvter.qft");
Log.i("wifilock", "multicastLock.isHeld() = " +wifilock.isHeld());
Log.i("wifilock", "multicastLock.toString() = " +wifilock.toString());
wifilock.acquire();
Log.i("wifilock", "multicastLock.isHeld() = " + wifilock.isHeld());
Log.i("wifilock", "multicastLock.toString() = " + wifilock.toString());
if (Settings.socket==null)
{
initsocket();
}
UdpServer udpserver = new UdpServer();
udpserver.start();
在udpserver类
下public volatile boolean keepServerRunning=true;
public void run()
{
boolean none=true;
try {
byte[] buffer = new byte[Settings.udppacketsize];
while (keepServerRunning==true)
{
DatagramPacket inpacket = new DatagramPacket(buffer,buffer.length);
Settings.socket.setSoTimeout(1000);
try
{
Settings.socket.receive(inpacket);
none=false;
}
catch (SocketTimeoutException e)
{
none=true;
}
if (none==false)
{
handler handler = new handler(Settings.socket, inpacket);
handler.start();
}
}
Settings.socket.close();
} catch (IOException e)
{
}
}
登录wifilock给出:
02-01 16:34:07.516 17365-17365/com.test.oappi.qft I/Wifilock﹕ multicastLock.isHeld() = false
02-01 16:34:07.516 17365-17365/com.test.oappi.qft I/wifilock﹕ multicastLock.toString() = MulticastLock{ 425b3ff8; refcounted: refcount = 0 }
02-01 16:34:07.516 17365-17365/com.test.oappi.qft I/wifilock﹕ multicastLock.isHeld() = true
02-01 16:34:07.516 17365-17365/com.test.oappi.qft I/wifilock﹕ multicastLock.toString() = MulticastLock{ 425b3ff8; held; refcounted: refcount = 1 }
清单权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
由于wifi状态肯定会发生变化,这是否意味着我真的有两部Android手机无法接收广播消息,或者API版本我尝试开发物质,因为我正在尝试开发到Api lvl 10.如果有人知道如何检查设备广播接收能力请告诉它。