我想通过 UDP 协议将按钮状态、操纵杆值等数据从我的应用程序重复发送到服务器来控制无人机,我搜索并尝试了无限 while 循环方法,但它使我的应用程序崩溃。我对工作没有太多了解,我只想要一个客户端在后台连续发送字符串/JSON对象作为数据报到定义的IP和端口。欢迎客户提供任何代码片段或建议。谢谢。 目前正在使用 Asynctask,但有人告诉我它已被弃用并且不适合。代码如下。 (转发)
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
public class UDP_Client {
public String Message;
@SuppressLint({"NewApi", "StaticFieldLeak"})
public void sendUDP() {
AsyncTask<Void, Void, Void> async_cient = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params){
try (DatagramSocket ds = new DatagramSocket()) {
DatagramPacket dp;
dp = new DatagramPacket(Message.getBytes(), Message.length(), InetAddress.getByName("192.168.***.***"), 3000);
ds.setBroadcast(true);
ds.send(dp);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
};
async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
如果你想在后台运行它。您需要使用服务。
我在我的主要活动中的一个单独的线程中用一段时间(无限循环)完成了它。而且效果很好!
new Thread( new Runnable() { @Override public void run() {
while(true) {
// Execute if mainSwitch is "ON"
if(mainSwitchOn[0]) {
// Creating new UDP_Client class object and accessing the public message variable to send data through
// sendUDP() function
Intent i = getIntent();
String IpAddr = i.getStringExtra("IpAddr");
UDP_Client Client = new UDP_Client();
Client.Message = output;
Client.IpAddress = IpAddr;
Client.sendUDP();
try {
// Giving 2ms sleep time to update values in thread.
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} } ).start();