简体   繁体   中英

Continuously send UDP packets in background in Java

I want to send the data like button states, joystick values, etc from my app to a server repeatedly through UDP protocol to control a drone, I searched and tried the infinite while loop approach but it makes my app crash. I do not have much knowledge about working, I just want a Client that sends a string/JSON object continuously in the background as a datagram to defined IP and port. Any code snippets of the client or suggestions are welcome. Thank you. Currently using Asynctask, but someone told me it's deprecated and not suitable. The code is given below. (reposting)

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);
    }
}

If you want to run it on background. You need to use service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM