Android之蓝牙那些事

来源:互联网 发布:蚁群算法实现 编辑:程序博客网 时间:2024/05/16 23:33

1,如何开启蓝牙:

①,简单粗暴的方式: ba.enable();

这种方式固然简单,但有一些问题,对于6.0以上版本,权限是重大问题,调用enable();后会有权限提示弹出框,如果你拒接就无法开启。

②,推荐开启方式:

Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler, 0);

会有返回值,你根据返回值做相应的处理即可,if (requestCode == 0) {//蓝牙状态
if (resultCode == RESULT_CANCELED) {//取消
openOrclose = false;
} else {//开启
openOrclose = true;
btn_open_close.setText("开启");
}
}

这样可以避开权限,防止用户拒绝权限开启,根据返回码来判断是否开启成功。

推荐第二种方法。

2,如何关闭蓝牙:

ba.disable();就这样一个方法。

3,如何判断设备是否支持蓝牙:

ba = BluetoothAdapter.getDefaultAdapter();
if (ba == null) {
MyToast("改设备不支持蓝牙功能");
return;
}

就是判断你是不是能得到蓝牙对象来判断设备是否支持蓝牙。

4,如何得到蓝牙的名称:

tv_myname.setText("蓝牙名称:" + ba.getName());

5,设置蓝牙的可见性

蓝牙的可见性跟手机厂商有一点的联系,比如华为手机蓝牙的可见性有时间限制,小米的就没有限制,一直可见。

/**
* 设置蓝牙可见时间(跟timeout没有关系)
* @param timeout
*/
public void setDiscoverableTimeout(int timeout) {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
try {
Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
setDiscoverableTimeout.setAccessible(true);
Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
setScanMode.setAccessible(true);

setDiscoverableTimeout.invoke(adapter, timeout);
setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, timeout);
} catch (Exception e) {
e.printStackTrace();
}
}

关闭可见:

/**
* 隐藏蓝牙
*/
public void closeDiscoverableTimeout() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
try {
Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
setDiscoverableTimeout.setAccessible(true);
Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
setScanMode.setAccessible(true);

setDiscoverableTimeout.invoke(adapter, 1);
setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE, 1);
} catch (Exception e) {
e.printStackTrace();
}
}

6,如何获取周边蓝牙:

7,如何连接周边蓝牙:

8,如何取消蓝牙连接:

9,如何传递资源:


//-------end--------

0 0
原创粉丝点击