步骤:
/**注册搜索蓝牙receiver*/
mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);mFilter.addAction(BluetoothDevice.ACTION_FOUND);
mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mReceiver, mFilter);
// 如果正在搜索,就先取消搜索
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
mBluetoothAdapter.startDiscovery();
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/** 搜索到的蓝牙设备*/
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 搜索到的不是已经配对的蓝牙设备
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
BlueDevice blueDevice = new BlueDevice();
blueDevice.setName(device.getName());
blueDevice.setAddress(device.getAddress());
blueDevice.setDevice(device);
setDevices.add(blueDevice);
blueAdapter.setSetDevices(setDevices);
blueAdapter.notifyDataSetChanged();
Log.d(MAINACTIVITY, "搜索结果......"+device.getName());
}
/**当绑定的状态改变时*/
} else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
/**搜索完成*/
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
setProgressBarIndeterminateVisibility(false);
Log.d(MAINACTIVITY, "搜索完成......");
hideProgressDailog();
}
}
};
/**
* 开始连接蓝牙设备
*/
private void contectBuleDevices() {
/**使用A2DP协议连接设备*/
mBluetoothAdapter.getProfileProxy(this, mProfileServiceListener, BluetoothProfile.A2DP);
}
/**
* 连接蓝牙设备(通过监听蓝牙协议的服务,在连接服务的时候使用BluetoothA2dp协议)
*/
private BluetoothProfile.ServiceListener mProfileServiceListener = new BluetoothProfile.ServiceListener() {
@Override
public void onServiceDisconnected(int profile) {
}
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
try {
if (profile == BluetoothProfile.HEADSET) {
....
} else if (profile == BluetoothProfile.A2DP) {
/**使用A2DP的协议连接蓝牙设备(使用了反射技术调用连接的方法)*/
a2dp = (BluetoothA2dp) proxy;
if (a2dp.getConnectionState(currentBluetoothDevice) != BluetoothProfile.STATE_CONNECTED) {
a2dp.getClass()
.getMethod("connect", BluetoothDevice.class)
.invoke(a2dp, currentBluetoothDevice);
Toast.makeText(MainActivity.this,"请连接",Toast.LENGTH_SHORT).show();
getBondedDevices();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
1
2