1、字節數組轉換為字符串
byte[] byBuffer = new byte[20];
... ...
String strRead = new String(byBuffer);
strRead = String.copyValueOf(strRead.toCharArray(), 0, byBuffer.length]);
2、字符串轉換成字節數組
byte[] byBuffer = new byte[200];
String strInput="abcdefg";
byBuffer= strInput.getBytes();
注意:如果字符串里面含有中文,要特別注意,在Android系統下,默認是UTF8編碼,一個中文字符相當於3個字節,只有gb2312下一個中文相當於2字節。這種情況下可采取以下辦法:
byte[] byBuffer = new byte[200];
String strInput="我是字符串";
byBuffer= strInput.getBytes("gb2312");
主界面代碼
package my.work.Library; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; public class WsnActivty extends Activity { /** Called when the activity is first created. */ private Button btnNetwork; private String strIpAddr = null; static TextView textTips,seat; private ClientThread clientThread = null; private Message MainMsg; public static Handler mainHandler; static final int TIPS_UPDATE_UI = 3; //tips_update_ui static final int SEAT_UPDATE_UI = 6; //seat_update_ui static final int MAX_NODE = 4; static byte NodeData[][] = new byte[MAX_NODE][5];; // [5] 0=溫度 1=濕度 2=氣體 3=燈 static final int RX_DATA_UPDATE_UI = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initControl(); initMainHandler(); } private void initControl() { // TODO Auto-generated method stub btnNetwork = (Button) findViewById(R.id.btn_network); btnNetwork.setOnClickListener(new ButtonClick()); textTips = (TextView) findViewById(R.id.Tips); textTips.setText(R.string.init_tips); seat = (TextView) findViewById(R.id.statc001); seat.setText(R.string.people1); } class ButtonClick implements OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_network: // 連接網絡 showDialog(WsnActivty.this); break; } } } // 顯示連接對話框 private void showDialog(Context context) { final EditText editIP = new EditText(context); editIP.setText("192.168.0.10"); AlertDialog.Builder builder = new AlertDialog.Builder(context); // builder.setIcon(R.drawable.ic_launcher); builder.setTitle("請輸入服務器IP地址"); builder.setView(editIP); builder.setPositiveButton("連接", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { strIpAddr = editIP.getText().toString(); boolean ret = isIPAddress(strIpAddr); if (ret) { textTips.setText("服務器IP地址:" + strIpAddr); } else { strIpAddr = null; textTips.setText("IP地址不合法,請重新設置"); return; } clientThread = new ClientThread(strIpAddr);// 建立客戶端線程 clientThread.start(); //mainTimer = new Timer();// 定時查詢所有終端信息 //setTimerTask(); } }); builder.setNeutralButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (clientThread != null) { MainMsg = ClientThread.childHandler .obtainMessage(ClientThread.RX_EXIT); ClientThread.childHandler.sendMessage(MainMsg); textTips.setText("與服務器斷開連接"); } } }); builder.show(); } // 判斷輸入IP是否合法 private boolean isIPAddress(String ipaddr) { boolean flag = false; Pattern pattern = Pattern .compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b"); Matcher m = pattern.matcher(ipaddr); flag = m.matches(); return flag; } void initMainHandler() { mainHandler = new Handler() { // 主線程消息處理中心 public void handleMessage(Message msg) { switch (msg.what) { case TIPS_UPDATE_UI: String str = (String) msg.obj; //連接成功 textTips.setText(str); break; case SEAT_UPDATE_UI: String strseat = (String) msg.obj; //連接成功 seat.setText(strseat); break; } super.handleMessage(msg); } }; } }
子線程代碼
package my.work.Library; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.widget.Toast; public class ClientThread extends Thread { private OutputStream outputStream = null; private InputStream inputStream = null; private Socket socket; private SocketAddress socketAddress; public static Handler childHandler; private boolean RxFlag = true; final int TEXT_INFO = 12; static final int RX_EXIT = 11; static final int TX_DATA = 10; Context mainContext; Message msg; private String strIP; final int SERVER_PORT = 33333; byte cNodeData[][] = new byte[4][5]; // [5] 0=溫度 1=濕度 2=氣體 3=燈 int RxCount = 0, nRecvLen, index = 0; byte CheckSum; // byte strRxBuf[] = new byte[256]; int ucRecvLen = 7; private RxThread rxThread; //獲取WsnActivty.java 開辟子線程clientThread對象線程傳遞過來的ip地址 public ClientThread(String ip) { strIP = ip; } // 連接網絡 void connect() { RxFlag = true; socketAddress = new InetSocketAddress(strIP, SERVER_PORT); socket = new Socket(); try { socket.connect(socketAddress, SERVER_PORT); inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); msg = WsnActivty.mainHandler.obtainMessage( WsnActivty.TIPS_UPDATE_UI, "連接成功"); WsnActivty.mainHandler.sendMessage(msg); rxThread = new RxThread(); rxThread.start(); } catch (IOException e) { try { sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } msg = WsnActivty.mainHandler.obtainMessage( WsnActivty.TIPS_UPDATE_UI, "無法連接到服務器"); WsnActivty.mainHandler.sendMessage(msg); e.printStackTrace(); } catch (NumberFormatException e) { } } void initChildHandler() { Looper.prepare(); // 在子線程中創建Handler必須初始化Looper childHandler = new Handler() { // 子線程消息處理中心 public void handleMessage(Message msg) { // 接收主線程及其他線程的消息並處理... /** * MainMsg = ClientThread.childHandler.obtainMessage(ClientThread.TX_DATA, * len, 0, (Object) buffer); * SendData(SendBuf, 7); */ switch (msg.what) { case RX_EXIT: RxFlag = false; try { if (socket.isConnected()) { inputStream.close(); outputStream.close(); socket.close(); } } catch (IOException e1) { e1.printStackTrace(); } childHandler.getLooper().quit();// 結束消息隊列 break; default: break; } } }; // 啟動該線程的消息隊列 Looper.loop(); } public void run() { connect(); initChildHandler(); msg = WsnActivty.mainHandler.obtainMessage(WsnActivty.TIPS_UPDATE_UI, "與服務器斷開連接"); WsnActivty.mainHandler.sendMessage(msg); } // socket 接收線程 public class RxThread extends Thread { public void run() { try { while (socket.isConnected() && RxFlag) { byte strRxBuf[] = new byte[30]; byte i; int RxIndex, len, readBytes = 0; // msg = WsnActivty.mainHandler.obtainMessage( // WsnActivty.SEAT_UPDATE_UI, "有人"); // WsnActivty.mainHandler.sendMessage(msg); // len = inputStream.read(strRxBuf, readBytes, ucRecvLen - readBytes); String strRead = new String(strRxBuf); strRead = String.copyValueOf(strRead.toCharArray(), 0, strRxBuf.length); msg = WsnActivty.mainHandler.obtainMessage( WsnActivty.SEAT_UPDATE_UI, strRead); WsnActivty.mainHandler.sendMessage(msg); } if (socket.isConnected()) socket.close(); } catch (IOException e) { e.printStackTrace(); } } } byte GetDataLen(byte fc) { byte len = 0; switch (fc) { case 0x01: len = 22; break; case 0x07: case 0x08: case 0x0A: case 0x0B: case 0x0C: case 0x0D: len = 7; break; } return len; } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/Tips" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/init_tips" android:textSize="40px" android:textColor="#00ff00" /> <Button android:id="@+id/btn_network" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/login" android:textSize="40px" android:textColor="#00ff00" /> <TextView android:id="@+id/statc001" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40px" android:textColor="#00ff00" /> <TextView android:id="@+id/statc002" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40px" android:textColor="#00ff00" /> <TextView android:id="@+id/statc003" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40px" android:textColor="#00ff00" /> <TextView android:id="@+id/statc004" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40px" android:textColor="#00ff00" /> <TextView android:id="@+id/statc005" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40px" android:textColor="#00ff00" /> </LinearLayout>
string.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="login">連接服務器</string> <string name="app_name">梧州學院圖書館刷卡入座系統</string> <string name="move">獲取視頻流</string> <string name="init_tips">提示:請先打開WiFi或GPRS再連接網絡</string> <string name="people1">空座</string> <string name="people2">有人</string> </resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.work.Library" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".WsnActivty" 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> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> </manifest>