0

我对编写 Android 应用程序很陌生,我想编写一段代码,以定期间隔(比如 1 秒)广播传感器数据。搜索开源代码,我设法编写了一个发送者类,如下所示:

public class Sender extends Thread {
    private static final String TAG = "Sending";
    private static final int PORT = 12346;
    private static final int TIMEOUT_MS = 500;
    private static final int BUF_SIZE = 1024;
    private WifiManager mWifi;

    Sender(WifiManager wifi) {
        mWifi = wifi;
    }

    public void run() {
        try {
            DatagramSocket socket = new DatagramSocket(PORT);
            socket.setBroadcast(true);
            socket.setSoTimeout(TIMEOUT_MS);
            sendData(socket);
            socket.close();
            Thread.sleep(1000);
        }
        catch (IOException ioe) {
            Log.e(TAG, "Couldn't send data", ioe);
        } 
        catch (InterruptedException ie) {
            Log.e(TAG,  "Can't sleep", ie);
        }
    }

    private void sendData(DatagramSocket socket) throws IOException {
        byte[] buf = new byte[BUF_SIZE];
        buf = object.toString().getBytes();
        InetAddress addr = InetAddress.getByName("192.168.0.255"); // TO FIX
        DatagramPacket packet = new DatagramPacket(buf, buf.length, addr, PORT);
        socket.send(packet);
    }

    public void main(String[] args) {
        new Sender(null).start();
        while (true) {
        }
    }
}

下面是我从 onCreate 方法中启动它的方法:

public void onCreate(Bundle savedInstanceState) {
...

    new Sender((WifiManager) getSystemService(Context.WIFI_SERVICE)).start();
...
}

现在,如果我在笔记本电脑上打开 Wireshark,我只会看到应用程序启动时发送的一个数据包,而不是每秒钟发送一次。

有人可以指出我做错了什么吗?老实说,我对线程和东西不太熟悉,所以我可能只是在这里遗漏了一些明显的东西......

编辑

好的,所以必须循环运行方法。请参阅下面答案中的更正代码。

4

1 回答 1

2

这是更正后的运行方法代码:

public void run() {
            while (true) {
                try {
                    DatagramSocket socket = new DatagramSocket(PORT);
                    socket.setBroadcast(true);
                    socket.setSoTimeout(TIMEOUT_MS);
                    sendData(socket);
                    socket.close();
                    Thread.sleep(1000);
                }
                catch (IOException ioe) {
                    Log.e(TAG, "Couldn't send data", ioe);
                } 
                catch (InterruptedException ie) {
                    Log.e(TAG,  "Can't sleep", ie);
                }
            }
}
于 2012-04-15T08:14:56.063 回答