在Android应用中通过UDP套接字接收数据,主要涉及到以下几个基础概念:
DatagramSocket
类用于发送和接收UDP数据包。以下是一个简单的示例代码,展示如何在Android应用中通过UDP套接字接收数据:
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "UDPReceiver";
private static final int PORT = 5000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(PORT);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
Log.d(TAG, "Received: " + received);
}
} catch (SocketException e) {
Log.e(TAG, "SocketException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
}
}
}).start();
}
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE}, REQUEST_CODE);
}
请注意,上述代码示例仅用于演示目的,在实际应用中可能需要更多的错误处理和优化。
领取专属 10元无门槛券
手把手带您无忧上云