手机蓝牙

<1>蓝牙相关的API

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

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

<2>在AndroidManifest.xml声明蓝牙权限:<user-permission android:name="android.permission.BLUETOOTH" />

 <3>扫描已配对的蓝牙设备

       1.获得BluetoothAdapter对象

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

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

       4.得到所有已经配对的蓝牙设备对象

    //得到BluetoothAdapter对象
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    //判断BluetoothAdapter对象是否为空
    if(adapter != null){
      //调用isEnable()方法,判断当前蓝牙设备是否可用
      if(!adapter.isEnabled()){
        //创建一个Intent对象启动一个Activity,提示用户开启蓝牙设备
        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 bluetoothDevice = (BluetoothDevice) iterator.next();
          System.out.println(bluetoothDevice.getAddress());
        }
      }
    }
    else{
      System.out.println("没有蓝牙设备");
    }

<4>修改蓝牙设备的可见性

        1.首先在AndroidManifest.xml文件中获得相应的权限:

    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

   2.MainActivity中的代码如下:

    //创建一个Intent对象,并将其action的值设置为BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE
    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    //将一个键值对存放到Intent对象当中,主要用于指定可见状态的持续时间
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
    startActivity(discoverableIntent);

<5>扫描周围的蓝牙设备

    //首先创建一个IntentFilter对象,将其action指定为BluetoothDevice。ACTION_FOUND
    IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    BluetoothReceiver bluetoothReceiver = new BluetoothReceiver();
    //注册广播接收器
    registerReceiver(bluetoothReceiver, intentFilter);

    private class BluetoothReceiver extends BroadcastReceiver{

      @Override
      public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        if(BluetoothDevice.ACTION_FOUND.equals(action)){
          //可以从收到的intent对象当中,将代表远程蓝牙适配器的对象取出
          BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
          System.out.println(device.getAddress());
        }
      }
    }

  监听事件:

    //开始扫描周围的蓝牙设备,每扫描到一个蓝牙设备就会发送一个广播,开始扫描是一个异步操作
    adapter.startDiscovery();

原文地址:https://www.cnblogs.com/zhanglei93/p/4801601.html