我需要不断地从Android应用程序广播UDP数据包,所以我创建了一个派生自TimerTask
的类。当我尝试从TimerTask
中更新UI元素时,应用程序崩溃,告诉我它在一个单独的线程上运行。
但是,当我尝试发送UDP数据包时,应用程序因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);
}
}
答案 0 :(得分:1)
您是否尝试过使用从TimerTask中重复调用的AsyncTask?
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50000); //execute in every 50000 ms
}
来自@Rasel
答案 1 :(得分:0)
@override
public void run() {
new SendTask().exectue(null,null,null);
}
class SendTask extends AsyncTask<Void,Void,Void> {
public void doInBackground(Void.. params) {
DatagramPacket packet = new DatagramPacket("Hello".getBytes().....);
_socket.send(packet);
}
}