关于Android Bluetooth 蓝牙的知识整理

蓝牙

简介

Bluetooth是目前使用的最广泛的无线通讯协议。主要针对短距离设备通讯(10M)。

常用于连接耳机,连接其他手机,电脑等。

相关的API

BluetoothAdapter:该类的对象代表了本地的蓝牙适配器。

BluetoothDevice:代表了一个远程的Bluetooth设备。

蓝牙设备扫描

权限声明

AndroidManifest.xml声明蓝牙权限:

<user-permission android:name=”android.permission.BLUETOOTH” />

代码实现

//获得BluetoothAdapter对象

BluetoothAdapter adapter =BluetoothAdapter.getDefaultAdapter();

//判断是否拥有蓝牙

if (adapter == null) {

       System.out.println("Device does not support Bluetooth"); //没有蓝牙

} else {

       System.out.println("Device support Bluetooth"); //有蓝牙

       //在有蓝牙的情况下,判断蓝牙是否打开

if (!adapter.isEnabled()) {             

              System.out.println("notEnable"); //没有打开

       Intent intent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE) ;

              startActivity(intent) ;

              } else {

              System.out.println("isEnable"); //已打开

       }

       //扫描所有蓝牙设备,得到的远程设备,存放在set集合中。

       Set<BluetoothDevice> set = adapter.getBondedDevices();

       if (set.size() > 0) {

              for (Iterator iterator = set.iterator(); iterator.hasNext();) {

                     BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator.next();

//输出设备的名字和MAC地址。

System.out.println(bluetoothDevice.getName()

+"---"+bluetoothDevice.getAddress());

              }

       }

}

 

设置蓝牙的可见性

权限声明:

<user-permission android:name=” android.permission.BLUETOOTH_ADMIN”/>

代码部分

Intent disIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE) ;

//当超过300秒的时候,默认覆盖为300

disIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500) ;

startActivity(disIntent);

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值