Android手机之间的蓝牙通信的代码和原理

来源:互联网 发布:三菱编程器fx20p 编辑:程序博客网 时间:2024/05/21 06:57

原理类似socket通信,必须有一个作为服务端,一个作为客户端。特别注意的两端的uuid必须相同。一下就是简单蓝牙聊天代码。源码下载地址:http://download.csdn.net/detail/cao185493676/9782519

1.客户端代码

package com.example.myblooth;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import java.util.UUID;import android.os.Bundle;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.bluetooth.BluetoothSocket;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.util.Log;import android.view.LayoutInflater;import android.view.Menu;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.BaseAdapter;import android.widget.EditText;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity implements OnItemClickListener {private BluetoothAdapter bAtapter;private BluetoothDevice device;private List<BluetoothDevice> deviceList = new ArrayList<BluetoothDevice>();private List<String> nameList = new ArrayList<String>();private ListView mListView;private BluetoothSocket bs;private EditText mEditText;private StringBuilder incoming = new StringBuilder();private TextView tv;private BluetoothSocket transferSocket;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mEditText = (EditText) findViewById(R.id.et_id);tv = (TextView) findViewById(R.id.tv_id);initView();}public void click(View view) {if (transferSocket != null) {String str = mEditText.getText().toString();sendMessage(transferSocket, "客户端说:" + str + "\n");}}private void initView() {// TODO Auto-generated method stubbAtapter = BluetoothAdapter.getDefaultAdapter();mListView = (ListView) findViewById(R.id.list_id);mListView.setOnItemClickListener(this);startDiscovery();mListView.setAdapter(baseAdapter);}private void startDiscovery() {// TODO Auto-generated method stubregisterReceiver(discoveryRsult, new IntentFilter(BluetoothDevice.ACTION_FOUND));deviceList.clear();nameList.clear();bAtapter.startDiscovery();}BroadcastReceiver discoveryRsult = new BroadcastReceiver() {@Overridepublic void onReceive(Context arg0, Intent arg1) {// TODO Auto-generated method stubnameList.add(arg1.getStringExtra(BluetoothDevice.EXTRA_NAME));deviceList.add((BluetoothDevice) arg1.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE));Log.i("caohaidemo", "nameList:" + nameList.size());baseAdapter.notifyDataSetChanged();}};BaseAdapter baseAdapter = new BaseAdapter() {@Overridepublic View getView(int arg0, View arg1, ViewGroup arg2) {arg1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.item, arg2, false);TextView tv = (TextView) arg1.findViewById(R.id.item_text);tv.setText(nameList.get(arg0));return arg1;}@Overridepublic long getItemId(int arg0) {// TODO Auto-generated method stubreturn arg0;}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn nameList.get(arg0);}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn nameList.size();}};@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {// TODO Auto-generated method stubfinal BluetoothDevice device = deviceList.get(arg2);new Thread() {@Overridepublic void run() {// TODO Auto-generated method stubconnectToServerSocket(device,UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));}}.start();}private void connectToServerSocket(BluetoothDevice device, UUID uuid) {try {BluetoothSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);transferSocket = clientSocket;// Block until server connection accepted.clientSocket.connect();runOnUiThread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubToast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_LONG).show();}});// Start listening for messages.listenForMessages(clientSocket, incoming);// Add a reference to the socket used to send messages.} catch (IOException e) {Log.e("BLUETOOTH", "Blueooth client I/O Exception", e);}}private void sendMessage(BluetoothSocket socket, String message) {OutputStream outStream;try {outStream = socket.getOutputStream();// Add a stop character.byte[] byteArray = (message + " ").getBytes();byteArray[byteArray.length - 1] = 0;outStream.write(byteArray);} catch (IOException e) {}}private boolean listening = false;private void listenForMessages(BluetoothSocket socket,final StringBuilder incoming) {listening = true;int bufferSize = 1024;byte[] buffer = new byte[bufferSize];try {InputStream instream = socket.getInputStream();int bytesRead = -1;while (listening) {bytesRead = instream.read(buffer);if (bytesRead != -1) {String result = "";while ((bytesRead == bufferSize)&& (buffer[bufferSize - 1] != 0)) {result = result + new String(buffer, 0, bytesRead - 1);bytesRead = instream.read(buffer);}result = result + new String(buffer, 0, bytesRead - 1);incoming.append(result);Log.i("caohaidemo", "服务器说:" + incoming.toString());runOnUiThread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtv.setText(incoming.toString());}});}}// socket.close();} catch (IOException e) {} finally {}}}


2.服务端代码:

package com.example.mybloothserver;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.UUID;import android.os.Bundle;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothServerSocket;import android.bluetooth.BluetoothSocket;import android.util.Log;import android.view.Menu;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {private EditText mEditText;private StringBuffer sb;private TextView tv;private StringBuilder incoming = new StringBuilder();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mEditText = (EditText) findViewById(R.id.et_id);sb = new StringBuffer();tv = (TextView) findViewById(R.id.tv_id);startServerSocket(BluetoothAdapter.getDefaultAdapter());}public void click(View view) {if (transferSocket != null) {String str = mEditText.getText().toString();sendMessage(transferSocket, "服务器说:" + str + "\n");}}private BluetoothSocket transferSocket;private UUID startServerSocket(BluetoothAdapter bluetooth) {UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");String name = "bluetoothserver";try {final BluetoothServerSocket btserver = bluetooth.listenUsingRfcommWithServiceRecord(name, uuid);Thread acceptThread = new Thread(new Runnable() {public void run() {try {// Block until client connection established.final BluetoothSocket serverSocket = btserver.accept();transferSocket = serverSocket;runOnUiThread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubToast.makeText(MainActivity.this, "连接成功",Toast.LENGTH_LONG).show();}});// Start listening for messages.listenForMessages(serverSocket, incoming);// Add a reference to the socket used to send messages.} catch (IOException e) {Log.e("BLUETOOTH", "Server connection IO Exception", e);}}});acceptThread.start();} catch (IOException e) {Log.e("BLUETOOTH", "Socket listener IO Exception", e);}return uuid;}/** * Listing 16-8: Sending and receiving strings using Bluetooth Sockets */private void sendMessage(BluetoothSocket socket, String message) {OutputStream outStream;try {outStream = socket.getOutputStream();// Add a stop character.byte[] byteArray = (message + " ").getBytes();byteArray[byteArray.length - 1] = 0;outStream.write(byteArray);} catch (IOException e) {}}private boolean listening = false;private void listenForMessages(BluetoothSocket socket,final StringBuilder incoming) {listening = true;int bufferSize = 1024;byte[] buffer = new byte[bufferSize];try {InputStream instream = socket.getInputStream();int bytesRead = -1;while (listening) {bytesRead = instream.read(buffer);if (bytesRead != -1) {String result = "";while ((bytesRead == bufferSize)&& (buffer[bufferSize - 1] != 0)) {result = result + new String(buffer, 0, bytesRead - 1);bytesRead = instream.read(buffer);}result = result + new String(buffer, 0, bytesRead - 1);incoming.append(result);runOnUiThread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtv.setText(incoming.toString());}});}// socket.close();}socket.close();} catch (IOException e) {} finally {}}}

                                             
2 0
原创粉丝点击