Android UDP demo

分享Android UDP 接收发送实例,需要注意的地方是把UDP收发核心代码另起线程,不要放在UI线程里,还有就是在AndroidManifest里加一个访问INTERNET权限。

资源下载地址 http://download.csdn.net/download/shenyuanqing/8199345


MainActivity.java

package com.example.androidudp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends Activity {
	private EditText edtSendInfo,edtReceiveInfo,edtSendIP,edtSendPort,edtReceivePort; 
	private CheckBox chkSendHex,chkReceiveHex;
	private String sendInfo,receiveInfo;
	private byte[] buf;	
	private Button btnListen;
	private Boolean listenStatus=false;
	private DatagramSocket socket;
	public Handler receiveHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edtSendInfo = (EditText) findViewById(R.id.edtSendInfo);
        edtReceiveInfo=(EditText)findViewById(R.id.edtReceiveInfo);
    	edtSendIP=(EditText)findViewById(R.id.edtSendIP);
    	edtSendPort=(EditText)findViewById(R.id.edtSendPort);
    	edtReceivePort=(EditText)findViewById(R.id.edtReceivePort);
    	chkSendHex=(CheckBox)findViewById(R.id.chkSendHex);
    	chkReceiveHex=(CheckBox)findViewById(R.id.chkReceiveHex);
    	btnListen=(Button)findViewById(R.id.btnListen);
		//与UDP数据接收线程通信更新UI线程中EditText控件中的内容
    	receiveHandler = new Handler()
		{										
			  public void handleMessage(Message msg)										
			  {		
				  edtReceiveInfo.setText(receiveInfo);	
			  }									
		};
    }
    //UDP数据发送线程
	public class udpSendThread extends Thread
	{
		@Override
		public void run()
		{
			try 
			{
				if(chkSendHex.isChecked())
				{
					buf=hexStringToBytes (edtSendInfo.getText().toString());
				}
				else
				{
					buf=edtSendInfo.getText().toString().getBytes();
				}
				if(listenStatus==false)
				{
					socket = new DatagramSocket(Integer.parseInt(edtSendPort.getText().toString()));
				}
				InetAddress serverAddr = InetAddress.getByName(edtSendIP.getText().toString());
				DatagramPacket outPacket = new DatagramPacket(buf, buf.length,serverAddr, Integer.parseInt(edtSendPort.getText().toString()));  
				socket.send(outPacket);
				socket.close();

			} catch (Exception e) 
			{
				// TODO Auto-generated catch block 			
			}  
		}
	}
	//UDP数据接收线程
	public class udpReceiveThread extends Thread
	{	
		@Override  
		public void run() 
		{  
			try 
			{  
				socket = new DatagramSocket(Integer.parseInt(edtReceivePort.getText().toString()));
				listenStatus=true;
				while(listenStatus)
				{
					byte[] inBuf= new byte[1024];
					DatagramPacket inPacket=new DatagramPacket(inBuf,inBuf.length);
					socket.receive(inPacket);
					if(chkReceiveHex.isChecked())
					{
						receiveInfo = bytes2HexString(inBuf,inPacket.getLength());	
					}
					else
					{
						receiveInfo = new String (inPacket.getData());
					}
                	Message msg = new Message();
                	receiveHandler
                	.sendMessage(msg);				
				}				
			} catch (Exception e) 
			{  
				// TODO Auto-generated catch block 
			}  
		}  
	}
	//发送按钮单击事件
	public void SendButtonClick(View source)
	{
		new udpSendThread().start();  
	}
	//监听按钮点击事件
	public void ListenButtonClick(View source)
	{	
		if(listenStatus==false)
		{
			btnListen.setText("停止监听");
			new udpReceiveThread().start();
		}
		else
		{
			btnListen.setText("开始监听");	
			socket.close();
			listenStatus=false;
			new udpReceiveThread().interrupt();
		}
	}
	//16进制字符串转byte[]
    public static byte[] hexStringToBytes(String str)
    {  
        if (str == null || str.equals(""))
        {  
            return null;  
        }  
        String hexString=str.replace(" ","");  
        hexString = hexString.toUpperCase();  
        int length = hexString.length() / 2;  
        char[] hexChars = hexString.toCharArray();  
        byte[] d = new byte[length];  
        for (int i = 0; i < length; i++) 
        {  
            int pos = i * 2;  
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
        }  
        return d;  
    }
    private static byte charToByte(char c) 
    {  
        return (byte) "0123456789ABCDEF".indexOf(c);  
    }
    //byte[]转16进制字符串
	public static String bytes2HexString(byte[] b,int len) 
	{  
        String ret = "";  
        for (int i = 0; i < len; i++)
        {  
        	String hex = Integer.toHexString(b[ i ] & 0xFF);  
        	if (hex.length() == 1) 
        	{  
        		hex = '0' + hex;  
        	}  
        	ret += hex.toUpperCase()+" ";  
        }  
        return ret;  
    } 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"   
    android:layout_height="match_parent"   
    android:orientation="vertical" >   
<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1">
	<TableRow>
		<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="SendIP:"/>
		<EditText   
    		android:id="@+id/edtSendIP"   
   			android:layout_width="wrap_content"   
   			android:layout_height="wrap_content" 
    		android:text="127.0.0.1"/>  
	</TableRow>
	<TableRow>
		<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="SendPort:"/>    
		<EditText   
    		android:id="@+id/edtSendPort"   
    		android:layout_width="wrap_content"   
    		android:layout_height="wrap_content" 
    		android:text="5188"/>    
	</TableRow>
	<TableRow>
		<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="SendInfo:"/>       
		<EditText   
    		android:id="@+id/edtSendInfo"   
    		android:layout_width="wrap_content"   
    		android:layout_height="wrap_content" 
    		android:text="Hello Android's UDP"/>  
	</TableRow>
</TableLayout>
<CheckBox 
    android:id="@+id/chkSendHex"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="16进制发送"/>
<Button
    android:id="@+id/btnSend"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="    发送    "
    android:onClick="SendButtonClick"
    android:layout_gravity="center"/>
<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="--上面为UDP发送部分--下面为UDP接收部分---------------"/>
<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1">
	<TableRow >
		<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="ReceivePort:"/>    
		<EditText   
    		android:id="@+id/edtReceivePort"   
    		android:layout_width="wrap_content"   
    		android:layout_height="wrap_content" 
    		android:text="5188"/>   
	</TableRow>
	<TableRow>
		<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="ReceiveInfo:"/>       
		<EditText   
    		android:id="@+id/edtReceiveInfo"   
    		android:layout_width="wrap_content"   
    		android:layout_height="wrap_content" 
    		android:text=""/>  
	</TableRow>
</TableLayout>
<CheckBox 
    android:id="@+id/chkReceiveHex"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="16进制接收"/>
<Button
   	android:id="@+id/btnListen"
   	android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="开始监听"
    android:layout_gravity="center"
    android:onClick="ListenButtonClick"/>  
</LinearLayout>


 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidudp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET" />  
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidudp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

效果图


Android Studio是一种集成开发环境(IDE),用于开发Android应用程序。在Android Studio中创建UDP(用户数据报协议)的示例非常简单。 首先,在Android Studio中创建一个新的Android项目。然后,创建一个新的Java类来处理UDP通信。该类必须继承自Thread。在类的run()方法中,可以编写UDP通信的逻辑代码。 在UDP通信中,需要创建一个DatagramSocket对象来发送接收数据包。可以使用DatagramPacket类来创建要发送的数据包,并使用DatagramSocket类的send()方法将数据包发送出去。使用receive()方法从DatagramSocket接收数据包。 下面是一个简单的UDP示例代码: ```java import java.net.DatagramPacket; import java.net.DatagramSocket; public class UdpDemo extends Thread { // 监听的端口号 private static final int PORT = 4444; @Override public void run() { try { // 创建DatagramSocket对象 DatagramSocket socket = new DatagramSocket(PORT); byte[] buffer = new byte[1024]; while (true) { // 创建接收数据包的对象 DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // 接收数据包 socket.receive(packet); // 处理接收到的数据 String receivedData = new String(packet.getData(), 0, packet.getLength()); System.out.println("Received data: " + receivedData); } } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码创建了一个UDP服务器,它在指定的端口上接收数据包,并将接收到的数据打印到控制台。 要在Android应用程序中使用该UDP示例,只需在应用程序的主活动中实例UdpDemo类并启动它即可。 通过以上步骤,您可以在Android Studio中创建一个简单的UDP示例程序。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值