最近刚开始接触Bluetooth 就写了个demo 但是貌似不太顺利,网上没有什么好的教材。
然后就遇到了一些问题: 开启扫描只能扫到设备,但是却扫描不到手机蓝牙。还有点击连接也不吐司。
还有就是有没有关于蓝牙方面的资料
比如:蓝牙从掉坑到上天之类的博客或者视频来一波
defaultAdapter = BluetoothAdapter.getDefaultAdapter();
defaultAdapter = BluetoothAdapter.getDefaultAdapter();
public void star_stop(){
if(defaultAdapter==null||!defaultAdapter.isEnabled()){
Intent it=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//弹窗提示
startActivityForResult(it,REQUEST_CODE);
}else{
defaultAdapter.disable();//关闭蓝牙
Toast.makeText(this, "蓝牙已关闭!", Toast.LENGTH_SHORT).show();
}
}
//扫描设备
public void setBLeScan(boolean info){
if(info){
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.e("TAG","扫描完毕~~~~~~~~~~~~~");
defaultAdapter.stopLeScan(leScanCallbackr);
}
},WAIT_TIME);
defaultAdapter.startLeScan(leScanCallbackr);
}else{
defaultAdapter.stopLeScan(leScanCallbackr);
}
}
public void initCallback(){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR2){
leScanCallbackr = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
Log.e("TAG","run_scan");
runOnUiThread(new Runnable() {
@Override
public void run() {
if((bluetoothDevice != null) && !TextUtils.isEmpty(bluetoothDevice.getName())){
if(!devices.contains(bluetoothDevice)){
devices.add(bluetoothDevice);
if(showDeviceAdapter!=null){
showDeviceAdapter.notifyDataSetChanged();
}
}
}
}
});
}
};
}else{
Toast.makeText(this, "该设备不支持", Toast.LENGTH_SHORT).show();
return;
}
}
public void adapter(){
showDeviceAdapter = new ShowDeviceAdapter(this,devices);
list.setAdapter(showDeviceAdapter);
final BluetoothGattCallback gattCallback = new BluetoothGattCallback(){
//当连接状态发生改变时
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (status != BluetoothGatt.GATT_SUCCESS) {
gatt.close();
if (bluetoothGatt != null) {
bluetoothGatt.disconnect();
bluetoothGatt.close();
bluetoothGatt = null;
}
}
if (newState == BluetoothGatt.STATE_CONNECTED) {
Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
Toast.makeText(MainActivity.this, "当前设备无法连接", Toast.LENGTH_SHORT).show();
gatt.close();
if (bluetoothGatt != null) {
bluetoothGatt.disconnect();
bluetoothGatt.close();
bluetoothGatt = null;
}
}
}
};
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
remoteDevice = defaultAdapter.getRemoteDevice(devices.get(i).getAddress());
if(remoteDevice==null){
Toast.makeText(MainActivity.this, "未找到对应的设备", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(MainActivity.this, "========="+devices.get(i).getAddress()+"===========", Toast.LENGTH_SHORT).show();
bluetoothGatt = remoteDevice.connectGatt(MainActivity.this, true, gattCallback);//连接设备
}
});
}