蓝牙简介
蓝牙是一种短距无线通信的技术规范,它最初的目标是取代现有的掌上电脑和移动电话等各种数字设备上的有线电缆连接
主要有以下特点:
带宽更宽; 射频信号更强; 功耗更低; 安全性更高等特点。
蓝牙通信过程
1.首先开启蓝牙
2.搜索可用设备
3.创建蓝牙socket,获取输入输出流
4.读取和写入数据
5.断开连接关闭蓝牙
蓝牙代码
服务器连接
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket
// because mmServerSocket is final.
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code.
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
Log.e(TAG, "Socket's listen() method failed", e);
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned.
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "Socket's accept() method failed", e);
break;
}
if (socket != null) {
// A connection was accepted. Perform work associated with
// the connection in a separate thread.
manageMyConnectedSocket(socket);
mmServerSocket.close();
break;
}
}
}
// Closes the connect socket and causes the thread to finish.
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
客户端连接
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket
// because mmSocket is final.
BluetoothSocket tmp = null;
mmDevice = device;
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
bluetoothAdapter.cancelDiscovery();
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
try {
mmSocket.close();
} catch (IOException closeException) {
Log.e(TAG, "Could not close the client socket", closeException);
}
return;
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
manageMyConnectedSocket(mmSocket);
}
// Closes the client socket and causes the thread to finish.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the client socket", e);
}
}
}
共同处理通讯处理类代码
package com.example.blue.connect;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private final Handler mHandler;
public ConnectedThread(BluetoothSocket socket, Handler handler) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
mHandler = handler;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
//一直读数据
while (true) {
try {
bytes = mmInStream.read(buffer);
if( bytes >0) {
Message message = mHandler.obtainMessage(Constant.MSG_GOT_DATA, new String(buffer, 0, bytes, "utf-8"));
mHandler.sendMessage(message);
}
Log.d("GOTMSG", "message size" + bytes);
} catch (IOException e) {
mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_ERROR, e));
break;
}
}
}
//发送数据
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
Constant常量类代码
public class Constant {
public static final String CONNECTTION_UUID = "00001101-0000-1000-8000-00805F9B34FB";
/**
* 开始监听
*/
public static final int MSG_START_LISTENING = 1;
/**
* 结束监听
*/
public static final int MSG_FINISH_LISTENING = 2;
/**
* 有客户端连接
*/
public static final int MSG_GOT_A_CLINET = 3;
/**
* 连接到服务器
*/
public static final int MSG_CONNECTED_TO_SERVER = 4;
/**
* 获取到数据
*/
public static final int MSG_GOT_DATA = 5;
/**
* 出错
*/
public static final int MSG_ERROR = -1;
}
BlueToothController蓝牙控制类代码
public class BlueToothController {
private BluetoothAdapter mAapter;
public BlueToothController() {
mAapter = BluetoothAdapter.getDefaultAdapter();
}
public BluetoothAdapter getAdapter() {
return mAapter;
}
/**
* 打开蓝牙
* @param activity
* @param requestCode
*/
public void turnOnBlueTooth(Activity activity, int requestCode) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(intent, requestCode);
// mAdapter.enable();
}
/**
* 打开蓝牙可见性
* @param context
*/
public void enableVisibly(Context context) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(discoverableIntent);
}
/**
* 查找设备
*/
public void findDevice() {
assert (mAapter != null);
mAapter.startDiscovery();
}
/**
* 获取绑定设备
* @return
*/
public List<BluetoothDevice> getBondedDeviceList() {
return new ArrayList<>(mAapter.getBondedDevices());
}
}
蓝牙设备adaptor代码DeviceAdapter
public class DeviceAdapter extends BaseAdapter {
private Context mContext;
private List<BluetoothDevice> mDate;
public DeviceAdapter(List<BluetoothDevice> Date, Context context){
mDate = Date;
mContext = context;
}
@Override
public int getCount() {
return mDate.size();
}
@Override
public Object getItem(int position) {
return mDate.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if(convertView==null){
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.deviceadapter_layout,null);
viewHolder.textView1 = (TextView)convertView.findViewById(R.id.textview1);
viewHolder.textView2 = (TextView)convertView.findViewById(R.id.textview2);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
//获取蓝牙设备
BluetoothDevice bluetoothDevice = (BluetoothDevice) getItem(position);
viewHolder.textView1.setText("Name="+bluetoothDevice.getName());
viewHolder.textView2.setText("Address"+bluetoothDevice.getAddress());
return convertView;
}
public class ViewHolder{
public TextView textView1;
public TextView textView2;
}
public void refresh(List<BluetoothDevice> data){
mDate = data;
notifyDataSetChanged();
}
}