如何获取UDP响应并将其显示为textview

时间:2019-11-12 05:09:44

标签: android

我正在创建一个无人机应用程序,可以在其中发送命令并控制该无人机,但无法接收该无人机的响应并将其显示在Textview上。请参阅下面的代码,以及他们提到的无人机文档的URL,以创建用于发送和接收无人机响应的客户端

URL:https://dl-cdn.ryzerobotics.com/downloads/Tello/Tello%20SDK%202.0%20User%20Guide.pdf

客户代码:

public class UDP_Client {

    private AsyncTask<String, String, String> async_cient;
    public String Message;
    public String droneResponse;

    @SuppressLint({"NewApi", "StaticFieldLeak"})
    public void sendMessage()
    {
        async_cient = new AsyncTask<String, String, String>()
        {
            @Override
            protected String doInBackground(String... params)
            {
                DatagramSocket ds = null;

                try
                {
                    byte[] ipAddr = new byte[]{ (byte) 192, (byte) 168,10, (byte) 1};
                    byte[] receivedata = new byte[1556];
                    InetAddress addr = InetAddress.getByAddress(ipAddr);
                    ds = new DatagramSocket(8889);
                    DatagramPacket dp = new DatagramPacket(Message.getBytes(), Message.getBytes().length, addr, 8889);
                    DatagramPacket rp= new DatagramPacket(receivedata,receivedata.length);
                    ds.setBroadcast(true);
                    ds.send(dp);
                    ds.receive(dp);
                    droneResponse= new String(receivedata, 0, dp.getLength());
                    publishProgress();

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    if (ds != null)
                    {
                        ds.close();
                    }
                }
                return null;
            }

            protected void onProgressUpdate(String... progress){
                MainActivity.TEXT_RESPONSE.setText(droneResponse);
            }

            protected void onPostExecute(String result)
            {
                super.onPostExecute(result);
            }
        };

        if (Build.VERSION.SDK_INT >= 11) async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else async_cient.execute();
    }
}

0 个答案:

没有答案