一、.Bluetooth是目前使用最广泛的无线通讯协议,主要针对短距离的设备,基本上十米以内,而且是中间无阻碍的才能达到十米,如果中间有阻碍可能不到十米。

二、Bluetooth相关 API

        1.BluetoothAdapter:本地蓝牙适配器。

        2.BluetoothDevice:远程的Bluetooth设备上的蓝牙

   注意:蓝牙功能不能运行在模拟器上,必须在拥有蓝牙的安卓手机上;并且还要有一台蓝牙设备的电脑

三、扫描已配对的蓝牙设备(让手机和电脑进行蓝牙配对)

      1.在manifest中声明蓝牙权限:android.permission.BLUETOOTH     这就代表了本应用内能够访问手机的蓝牙设备

      2.对已配对的蓝牙设备名字的获取

        1)获得BiuetoothAdapter对象

         2)判断当前设备中是否拥有蓝牙设备

         3)判断当前设备中的蓝牙设备是否已经打开

         4)得到所有已经配对的蓝牙对象(即BluetoothDecice)

        点击一个按钮后,代码如下:

//得到BluetoothAdapter对象
         BluetoothAdapter   adapter=BluetoothAdapter.getDefaultAdapter();
         //判断BluetoothAdapter对象是否为空,为空表示本机么有蓝牙设备
        if(adapter!=null){
        System.out.println("本机拥有蓝牙设备");
         //调用isEnable()方法,判断当前蓝牙设备是否可用
          if(!adapter.isEnabled()){
//设备 如果不可用,创建一个intent对象,来启动询问用户是否开启蓝牙设备
 Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
 startActivity(intent);
              }   
//得到所有已经配对的蓝牙适配器对象
Set<BluetoothDevice> devices=adapter.getBondedDevices();
        if(devices.size()>0){//通过迭代的方法获取出蓝牙设备的地址
for(Iterator iterator=devices.interator();interator.hasNext();){
BluetoothDevice bluetoothDevice=(BluetoothDevice) iterator.next();
                        System.out.println(bluetoothDevice.getAddress());
}
}
   }
   else{
       System.out.println("没有蓝牙设备");
}

 

四、修改蓝牙设备的可见性代码如下:

1.在manifest'中添加权限:android.permission.BLUETOOTH_ADMIN
        2.创建一个intent对象,并且将action的值设置为BluetoothAdapter。ACTION_REQUEST_DISCOVERABLE
            Intent discoverableIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            将一个键值对存放到intent中,主要用于指定可见状态的持续时间
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,500);
            startActivity(discoverableIntent);

五、扫描周围的蓝牙设备代码

        注意:蓝牙一次扫描大约需要12秒,功耗大(对电池耗电量大)

         1.bluetoothAdapter.startDiscovery();这句代码就是搜索周边设备蓝牙,这是一个异步调用,马上调用这个函数立马返回,并且还要发送广播


1)在oncreate方法中,
                  创建一个IntentFilter对象,将其action指定为BluetoothDevice.ACTION_FOUND
                  IntentFilter intentFilter =new IntentFilter(BluetoothDevice.ACTION_FOUND);
                  bluetoothAdapter=new BluetoothReceiver();
                  注册广播接收器
                   registerReceiver(bluetoothReceiver,intentFilter);
                2) 定义一个receiver的类接收广播
                   private class BluetoothReceiver extends BroadcastReceiver{
                              @Override
                               public void onReceive(Context context ,Intent intent) {
                                 String action =intent.getAction();
if(BuletoothDevice.ACTION_FOUND.equals(action)){
//可以从收到的intent对象中,将代表远程蓝牙适配器的对象取出
BuletoothDevice

                                         }
                              }  
                        }