https://github.com/Jasonchenlijian/FastBle
0.下载依赖库,添加库
1对蓝牙初始化和权限声明
1.1声明权限(AndroidManifest.xml中)
1.2在AndroidManifest.xml中还需要初始化蓝牙,我们新建一个class比如BleApplication,其中个代码如下:
@Override
public void onCreate() {
super.onCreate();
BleManager.getInstance().init(this);
BleManager.getInstance()
.enableLog(true)
.setMaxConnectCount(7)
.setOperateTimeout(5000);
1.3之后在AndroidManifest.xml中运用
2.在Activity中写蓝牙搜索,连接的代码
可以用一个BleManager变量,因为之后会用到很多次BleManager.getInstance();
private BleManager bleManager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bleManager = BleManager.getInstance();
2.1在生命周期onResume中 判断有无蓝牙连接,如果没有就开始检查蓝牙状态和搜索蓝牙.
这有三个方法checkBluetoothState(), searchBluetoothDevices(),showConnectedDevice()
@Override
protected void onResume() {
super.onResume();
//检查蓝牙连接
if (BleManager.getInstance().getAllConnectedDevice().size() == 0){
checkBluetoothState();
searchBluetoothDevices();
}else
{
showConnectedDevice();
}
}
2.2几个方法的代码:
2.2.1checkBluetoothState()
//检测蓝牙打开情况
private void checkBluetoothState(){
if (!bleManager.isBlueEnable()){
//判断是否打开蓝牙
AlertDialog.Builder builder = new AlertDialog.Builder(BleSearchActivity.this);
builder.setTitle(R.string.ble_tips) //标题
.setMessage(R.string.ble_connect_suggestion) //提示内容
.setPositiveButton(R.string.positive_bt, new DialogInterface.OnClickListener() { //确定按钮
@Override
public void onClick(DialogInterface dialog, int which) {