I need to continously broadcast UDP packets from a Android application, so I created a class that derives from TimerTask
. When I try to update a UI element from within my TimerTask
, the app crashes which tells me that it runs on a separate thread.
However, when I'm trying to send a UDP packet, the app crashes because of a NetworkOnMainThreadException
.
// simplified
public class UdpDiscoveryTask extends TimerTask {
private final DatagramSocket _socket;
public UdpDiscoverytAsk() {
_socket = new DatagramSocket(PORT);
}
@Override
public void run() {
DatagramPacket packet = new DatagramPacket("Hello".getBytes().....);
_socket.send(packet);
}
}