我需要不断地从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);
}
}发布于 2014-08-24 22:09:05
您是否尝试过使用从AsyncTask中多次调用的TimerTask?
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
发布于 2014-08-24 22:07:53
@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);
}
}https://stackoverflow.com/questions/25476756
复制相似问题