Android UDP demo

来源:互联网 发布:矩阵运算公式 编辑:程序博客网 时间:2024/05/29 17:21

分享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{@Overridepublic 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>

效果图


0 0
原创粉丝点击