android蓝牙相关
2017-03-20 本文已影响95人
dong_hui
1.android蓝牙的几个基本概念
- 权限
<uses-permissionandroid:name="[Android](http://lib.csdn.net/base/android).permission.BLUETOOTH" />
允许程序连接到已配对的蓝牙设备。
<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" />
允许程序发现和配对蓝牙设备。
- 操作蓝牙主要用到的类 BluetoothAdapter类,使用时导包
import android.bluetooth.BluetoothAdapter;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- 开启蓝牙
if(!mBluetoothAdapter.isEnabled()){
//弹出对话框提示用户是后打开
Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler, REQUEST_ENABLE);
//不做提示,直接打开,不建议用下面的方法,有的手机会有问题。
// mBluetoothAdapter.enable();
}
- 获取本地蓝牙信息
//获取本机蓝牙名称
String name = mBluetoothAdapter.getName();
//获取本机蓝牙地址
String address = mBluetoothAdapter.getAddress();
Log.d(TAG,"bluetooth name ="+name+" address ="+address);
//获取已配对蓝牙设备
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
Log.d(TAG, "bonded device size ="+devices.size());
for(BluetoothDevice bonddevice:devices){
Log.d(TAG, "bonded device name ="+bonddevice.getName()+" address"+bonddevice.getAddress());
}
- 搜索设备:
mBluetoothAdapter.startDiscovery();
开始搜索设备,该过程是异步的,通过下面注册广播接受者,可以监听是否搜到设备。
IntentFilter filter = new IntentFilter();
//发现设备
filter.addAction(BluetoothDevice.ACTION_FOUND);
//设备连接状态改变
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
//蓝牙设备状态改变
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBluetoothReceiver, filter);
- 监听扫描结果
private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG,"mBluetoothReceiver action ="+action);
if(BluetoothDevice.ACTION_FOUND.equals(action)){//每扫描到一个设备,系统都会发送此广播。
//获取蓝牙设备
BluetoothDevice scanDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(scanDevice == null || scanDevice.getName() == null) return;
Log.d(TAG, "name="+scanDevice.getName()+"address="+scanDevice.getAddress());
//蓝牙设备名称
String name = scanDevice.getName();
if(name != null && name.equals(VnApplication.BLUETOOTH_NAME)){
mBluetoothAdapter.cancelDiscovery();
//取消扫描
mProgressDialog.setTitle(getResources().getString(R.string.progress_connecting)); //连接到设备。
mBlthChatUtil.connect(scanDevice);
}
}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}
}
};
- 连接:
此方法中主要是获取socket客户端,并连接。
BluetoothSocket mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
mmSocket.connect();
- 连接成功后,获取输入输出流,进行通信
当连接成功后,connected(mmSocket, mmDevice); 获取输入输出流,从而进行通信。
private InputStream mmInStream = socket.getInputStream();
private OutputStream mmOutStream =socket.getOutputStream();
mmOutStream.write(buffer);发送信息。
mmInStream.read(buffer); 收到消息。