判断蓝牙是否连接

Android对于蓝牙开发从2.0版本的sdk才开始支持,而且模拟器不支持,测试至少需要两部手机,所以制约了很多技术人员的开发。
1. 首先,要操作蓝牙,先要在AndroidManifest.xml里加入权限
// 管理蓝牙设备的权限
<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" />
// 使用蓝牙设备的权限
<uses-permissionandroid:name="android.permission.BLUETOOTH" />
2.打开蓝牙
获得蓝牙适配器(android.bluetooth.BluetoothAdapter),检查该设备是否支持蓝牙,如果支持,就打开蓝牙。
[java]
// 检查设备是否支持蓝牙
adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null)
{
// 设备不支持蓝牙
}
// 打开蓝牙
if (!adapter.isEnabled())
{
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// 设置蓝牙可见性,最多300秒
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(intent);
}
// 检查设备是否支持蓝牙
adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null)
{
// 设备不支持蓝牙
}
// 打开蓝牙
if (!adapter.isEnabled())
{
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// 设置蓝牙可见性,最多300秒
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(intent);
}
3.获取已配对的蓝牙设备(android.bluetooth.BluetoothDevice)
首次连接某蓝牙设备需要先配对,一旦配对成功,该设备的信息会被保存,以后连接时无需再配对,所以已配对的设备不一定是能连接的。
[java]
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for(int i=0; i<devices.size(); i++)
{
BluetoothDevice device = (BluetoothDevice) devices.iterator().next();
System.out.println(device.getName());
}
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for(int i=0; i<devices.size(); i++)
{
BluetoothDevice device = (BluetoothDevice) devices.iterator().next();
System.out.println(device.getName());
}
4.搜索周围的蓝牙设备
适配器搜索蓝牙设备后将结果以广播形式传出去,所以需要自定义一个继承广播的类,在onReceive方法中获得并处理蓝牙设备的搜索结果。
[java]
// 设置广播信息过滤
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// 注册广播接收器,接收并处理搜索结果
context.registerReceiver(receiver, intentFilter);
// 寻找蓝牙设备,android会将查找到的设备以广播形式发出去
adapter.startDiscovery();
// 设置广播信息过滤
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// 注册广播接收器,接收并处理搜索结果
context.registerReceiver(receiver, intentFilter);
// 寻找蓝牙设备,android会将查找到的设备以广播形式发出去
adapter.startDiscovery(); 自定义广播类
[java]
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getName());
}
}
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getName());
}
}
}
5.蓝牙设备的配对和状态监视
[java]
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 获取查找到的蓝牙设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getName());
// 如果查找到的设备符合要连接的设备,处理
if (device.getName().equalsIgnoreCase(name)) {
// 搜索蓝牙设备的过程占用资源比较多,一旦找到需要连接的设备后需要及时关闭搜索
adapter.cancelDiscovery();
// 获取蓝牙设备的连接状态
connectState = device.getBondState();
switch (connectState) {
// 未配对
case BluetoothDevice.BOND_NONE:
// 配对
try {
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
break;
// 已配对
case BluetoothDevice.BOND_BONDED:
try {
// 连接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
} else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
// 状态改变的广播
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName().equalsIgnoreCase(name)) {
connectState = device.getBondState();
switch (connectState) {
case BluetoothDevice.BOND_NONE:
break;
case BluetoothDevice.BOND_BONDING:
break;
case BluetoothDevice.BOND_BONDED:
try {
// 连接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
}
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 获取查找到的蓝牙设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getName());
// 如果查找到的设备符合要连接的设备,处理
if (device.getName().equalsIgnoreCase(name)) {
// 搜索蓝牙设备的过程占用资源比较多,一旦找到需要连接的设备后需要及时关闭搜索
adapter.cancelDiscovery();
// 获取蓝牙设备的连接状态
connectState = device.getBondState();
switch (connectState) {
// 未配对
case BluetoothDevice.BOND_NONE:
// 配对
try {
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
break;
// 已配对
case BluetoothDevice.BOND_BONDED:
try {
// 连接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
} else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
// 状态改变的广播
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName().equalsIgnoreCase(name)) {
connectState = device.getBondState();
switch (connectState) {
case BluetoothDevice.BOND_NONE:
break;
case BluetoothDevice.BOND_BONDING:
break;
case BluetoothDevice.BOND_BONDED:
try {
// 连接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
}
} 6.蓝牙设备的连接
[java]
private void connect(BluetoothDevice device) throws IOException {
// 固定的UUID
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
UUID uuid = UUID.fromString(SPP_UUID);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
}
private void connect(BluetoothDevice device) throws IOException {
// 固定的UUID
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
UUID uuid = UUID.fromString(SPP_UUID);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
}

判断蓝牙是否连接

时间: 2024-08-07 15:26:29

判断蓝牙是否连接的相关文章

android开发之蓝牙配对连接的方法

最近在做蓝牙开锁的小项目,手机去连接单片机总是出现问题,和手机的连接也不稳定,看了不少蓝牙方面的文档,做了个关于蓝牙连接的小结. 在做android蓝牙串口连接的时候一般会使用 ? 1 2 3 4 5 6 7 8 BluetoothSocket tmp = null; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try {          tmp = device.createRfcom

iOS 判断网络是否连接

1 //判断网络是否连接 2 + (BOOL) connectedToNetwork 3 { 4 //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态 5 struct sockaddr_in zeroAddress; //struct用来向方法中传递复杂的参数(把参数当作对象,这样便于扩展) 6 bzero(&zeroAddress, sizeof(zeroAddress)); 7 zeroAddress.sin_len = sizeof(zeroAddress); 8 zeroAd

c# 判断网络是连接到互联网

方法1:InternetGetConnectedState [System.Runtime.InteropServices.DllImport("wininet")] private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue); private void button1_Click(object sender, EventArgs e) {

判断网络是否连接 和 判断GPS是否连接

//判断网络是否连接 public static Boolean isNetworkEnabled(Context context){ int status=-1  //设置默认连接的状态为-1 ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo = connec

Android判断网络是否连接

<!-- 配置文件判断网络是否连接 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> public static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Cont

iphone判断当前网络连接类型

?Reachability只能区分出无网络.wifi和wwan(2G&2.5G&3G)类型的网络连接类型,只需重构networkStatusForFlags方法,即可详细区分出2G与3G网络 ??1. [代码][C/C++]代码     //Reachability.m 中 networkStatusForFlags 方法重构- (NetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags{if ((fl

iOS 判断当前是否连接到网络和网络类型

之前有判断过是否连接到网络,没有使用apple的示例中的Reachability. #import <sys/socket.h> #import <netinet/in.h> #import <arpa/inet.h> #import <SystemConfiguration/SCNetworkReachability.h> -(BOOL)isConnectToNewtwork { struct sockaddr_in zeroAddress; bzero(

使用ConnectivityManager 判断网络是否连接

网络连接状态对那些依赖网络的APP是必须的.以下有两种方法实现了对网络的检查.组合使用效果更加 第一中方法:使用ConnectivityManager 检查网络连接 主要步骤: (1)获取ConnectivityManager对象. (2)使用ConnectivityManager对象的getActiveNetworkInfo获取NetworkInfo 对象. (3)使用ConnectivityManager对象的getNetworkInfo获取NetworkInfo对象,然后调用Network

如何 判断 设备 是否 连接 上 了 wifi

这里,我给出一个函数 1 public boolean sale_connect_check(WifiConfiguration wcg,Context context) { 2 boolean judge_2 = false;//二重判断的布尔变量 3 int wcgID = wifiManager.addNetwork(wcg);//获取所曾网络id 4 boolean judge = wifiManager.enableNetwork(wcgID, true);//就行操作,注意,网上很多