什么是蓝牙?
是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换,我们主要掌握这几项技能:
清单文件
打开蓝牙
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//打开蓝牙
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//允许被其他设备发现
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);//设置允许被搜索时间200s内可以被搜索到
startActivityForResult(intent, 201);
关闭蓝牙
bluetoothAdapter.disable();//关闭蓝牙
搜索蓝牙
bluetoothAdapter.startDiscovery();//搜索设备
显示已匹配的蓝牙
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
取消搜索
bluetoothAdapter.cancelDiscovery();//取消搜索
搜索其他蓝牙的广播
//注册蓝牙
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//扫描到远程设备
registerReceiver(myReceiver,intentFilter);
class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){//如果找到蓝牙的话
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(device!=null){
list_blue.add(device);
myAdapter2.notifyDataSetChanged();
}
}
}
}
蓝牙间的相互通信
服务端
new Thread(){
@Override
public void run() {
super.run();
try {
BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
while(true){
BluetoothSocket socket = serverSocket.accept();
new ServiceThread(handler,socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
/
public class ServiceThread extends Thread {
Handler handler;
BluetoothSocket socket;
public ServiceThread(Handler handler, BluetoothSocket socket) {
this.handler = handler;
this.socket = socket;
}
@Override
public void run() {
super.run();
try {
InputStream is = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
StringBuffer sb = new StringBuffer();
while ((len = is.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len));
Message obtain = Message.obtain();
obtain.what = 101;
obtain.obj = buffer;
handler.sendMessage(obtain);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务端
BluetoothDevice device = list.get(position);
try {
//创建socket
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
//connect 连接
socket.connect();
//发送数据
socket.getOutputStream().write("OPPO A3来了!".getBytes());
Toast.makeText(this, "发送成功!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
涉及到的类
BluetoothManager 蓝牙管理类,管理BluetoothAdapter。主要负责管理蓝牙的本地连接。
BluetoothAdapter 蓝牙适配器类:代表本蓝牙设备
BluetoothDevice 蓝牙设备,配对后的远程蓝牙设备.
BluetoothServiceSocket 服务端连接类
BluetoothSocket:客户端连接类
UUID(universal unique identifier , 全局唯一标识符)
格式如下:UUID格式一般是”xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,可到http://www.uuidgenerator.com 申请。UUID分为5段,是一个8-4-4-4-12的字符串,这个字符串要求永不重复。蓝牙建立连接时双方必须使用固定的UUID
例如:文件传输服务
OBEXFileTransferServiceClass_UUID = ‘{00001106-0000-1000-8000-00805F9B34FB}’