我有一个前台服务,该服务带有监视UDP数据包的线程。直到我将手机搁置约5分钟(但不完全是5分钟),然后它停止发送从UDP数据包获取的更新后,它才能正常工作。这是100%可复制的,而且我可以看到网络上的UDP数据包带有数据包捕获,因此我知道它们在那里。
private class ArduinoUDPListener extends Thread {
private MulticastSocket socket;
private AtomicBoolean done;
private Instant lastMsgTime;
public void run() {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyApp::MyWakelockTag");
wakeLock.acquire();
WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock multicastLock = null;
multicastLock = wm.createMulticastLock("udp for hamwin");
multicastLock.acquire();
WifiManager.WifiLock wifiLock = null;
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "wifi lock for ham");
wifiLock.acquire();
lastMsgTime = Instant.MIN;
done = new AtomicBoolean(false);
try {
socket = new MulticastSocket(7234);
InetAddress group = InetAddress.getByName("239.1.1.234");
socket.joinGroup(group);
socket.setReuseAddress(true);
socket.setBroadcast(true);
if (!socket.getBroadcast()) {
socket.close();
return;
}
socket.setSoTimeout(100);
byte[] buf = new byte[65535];
DatagramPacket p = new DatagramPacket(buf, 65535);
while (!done.get()) {
try {
socket.receive(p);
} catch (SocketTimeoutException e) {
// retry
continue;
} catch (IOException e) {
e.printStackTrace();
break;
}
// Process packet,
// sometimes we just stop getting here after a few minutes of normal activity if the phone is not touched.
if (mainThreadHdlr != null) {
Message msg = mainThreadHdlr.obtainMessage();
msg.obj = update;
mainThreadHdlr.sendMessage(msg);
Log.i("Net", "Sent update");
} else {
System.out.println("null?");
}
}
}
socket.close();
}
我还应该使用其他唤醒锁吗?我还有什么其他办法可以使网络/线程保持活动状态?我什至不知道它以什么方式停止了。网络?中央处理器?其他吗?
更新 添加了一些更详细的日志记录后,我发现总是会定期抛出SocketTimeoutException,但是当屏幕关闭时,UDP数据包会越来越少地发送到应用程序 !我期望每秒发送一个数据包,有时在屏幕关闭时它们不会到达〜5-10秒或更长时间。