Android学习笔记 - 蓝牙篇 (Bluetooth)

1.什么是蓝牙
  Bluetooth是目前使用的最广泛的无线通讯协议之一
  主要针对短距离设备通讯(10米)
  常用于连接耳机、鼠标和移动通讯设备等

 

2.发现周围蓝牙设备
  BluetoothAdapter:代表了本地的蓝牙适配器
  BluetoothDevice:代表一个远程的蓝牙设备
 
  扫描已配对的蓝牙设备方法:
  1.在AndroidManifest.xml声明蓝牙权限
  <uses-permission android:name="android.permission.BLUETOOTH" />
 
  2.获得BluetoothAdapter对象

  3.判断当前设备中是否拥有蓝牙设备

  4.判断当前设备中蓝牙设备是否已经打开

  5.得到已经配对的蓝牙设备对象
 

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if(btAdapter != null){
  if(btAdapter.isEnabled()){
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivity(intent);
    Set<BluetoothDevice> devices = adapter.getBondedDevices();
    if(devices.size() > 0){
      for(Iterator iterator = devices.iterator(); iterator.hasNext()){
        BluetoothDevice device = (BluetoothDevice)iterator.next();
        System.out.println(bluetoothDevice.getAddress());
      }
    }
    else System.out.println("没有绑定的蓝牙设备");
  }
  else System.out.println("蓝牙设备未正常启动");
}
else System.out.println("无蓝牙设备");

 

3.修改本机蓝牙设备的可见性

  Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); //可见持续300秒,不能超过300秒
  startActivity(intent);


4.扫描周围可用的蓝牙设备
 

  //1.注册一个广播,用于接收“发现设备”的广播
  IntentFilter intentFilter = IntentFilter(BluetoothAdapter.ACTION_FOUND);
  BluetoothReceiver receiver = new BluetoothReceiver();
  registerReceiver(receiver, intentFilter);
  
  //2.创建蓝牙适配器,并开始扫描
  BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
  btAdapter.startDiscovery();
  
  //3.继续广播接收类,处理接收到的广播
  private class BluetoothReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent){
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      System.out.println(device.getAddress());
    }
  }


 

 

 

 

你可能感兴趣的:(android,null,iterator,Class,通讯)