我已经为设备创建了后台服务来连接和读取广告包。扫描蓝牙低功耗扫描仪后我收到的设备显示在列表视图中。但是每当我点击ListView项目时,尽管在获取地址后运行服务,设备仍然无法连接。对于设备的连接我正在使用这种方法
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
Toast.makeText(this, "Unable to connect", Toast.LENGTH_SHORT).show();
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallBack);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
我试图达到该方法的方法就是研究员。在DeviceActivity中
Intent gattServiceIntent = new Intent(this, LeBluetoothService.class);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(context, "you clicked", Toast.LENGTH_SHORT).show();
device = mLeDeviceListAdapter.getDevice(position);
mDeviceAddress = device.getAddress();
bindService(gattServiceIntent, mServiceConnection, BIND_ABOVE_CLIENT);
mScanning = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
// mLeBluetoothService.connect(mDeviceAddress);
// Toast.makeText(context, "connected to: "+mDeviceAddress, Toast.LENGTH_SHORT).show();
}
});
对于自动服务连接,我使用以下代码。
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mLeBluetoothService = ((LeBluetoothService.LocalBinder) service).getService();
if (!mLeBluetoothService.initialize()) {
Toast.makeText(context, "Unable to initialize Bluetooth", Toast.LENGTH_SHORT).show();
finish();
}
mLeBluetoothService.connect(mDeviceAddress);
Toast.makeText(context, "Connected to " + mDeviceAddress, Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mLeBluetoothService = null;
}
};
当我尝试直接从列表视图连接时,它给我Null指针异常。
试试这个库https://github.com/Jasonchenlijian/FastBle它给你简单的方法