前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android 蓝牙操作详解

Android 蓝牙操作详解

作者头像
hbbliyong
发布2018-03-06 11:05:55
1.6K0
发布2018-03-06 11:05:55
举报
文章被收录于专栏:hbbliyonghbbliyonghbbliyong

1.启用蓝牙并使设备处于可发现状态    

   1.1 在使用BluetoothAdapter类的实例进操作之前,应启用isEnable()方法检查设备是否启用了蓝牙适配器。

    // 使用意图提示用户启用蓝牙,并使设备处于可发现状态

 private void startBluetooth() {
          BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
  // 检测蓝牙是否开启
  if (!bt.isEnabled()) {
              Intent enableIntent = new Intent(
                        BluetoothAdapter. ACTION_REQUEST_ENABLE);
              startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
          }
     }

 1.2返回意图活动时,调用onActivityResult(),可以提取主设备名称和mac地址

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == REQUEST_ENABLE_BT
                   && resultCode == Activity. RESULT_OK) {
              BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
              String address = bt.getAddress();
              String name = bt.getName();
              String toastText = name + " :" + address;
              Toast. makeText(this, toastText, Toast.LENGTH_LONG).show();
              discoverable();
          }
     }

1.3 请求用户授权,让设备可被其它临近设备发现:

 // 请求用户授权,让设备在120秒内处于可发现状态
 private void discoverable() {
          Intent discoverableIntent = new Intent(
 BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
          startActivity(discoverableIntent);
     }

2.连接启用蓝牙设备

 2.1对于任何蓝牙应用,都必须在AndroidManifst.xml中添加如下权限:

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

2.2 创建到其他蓝牙设备的套接字连接

     我们应该在一个线程内持续监听套接字流中的数据。可以在该线程外写入连接的流。这种连接是一个阻塞调用,由于蓝牙设备发现是一个缓慢的过程,可能降低连接速率。所以,在连接其它设备之前要取消设备发现。

     蓝牙套接字连接时阻塞调用,只在连接成功或者连接设备发生异常时才会返回。BluetoothConnection一经实例化,就会创建到其他设备的连接,并开始监听来自连接设备的数据。

package com.example.blueoothdemo;

 import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.UUID;

 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothDevice;
 import android.bluetooth.BluetoothSocket;

 /**
 * 读写蓝牙设备
 *
 * @author hbbliyong
 *
 */
 public class BluetoothConnecion extends Thread {
      private final BluetoothSocket mSocket;
      private final InputStream mInStream;
      private final OutputStream mOutStream;
      byte[] buffer;
      private final BluetoothAdapter mAdapter;
      // 用于本应用程序唯一的UUID,
      private static final UUID MY_UUID = UUID
                .fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

      public BluetoothConnecion(BluetoothDevice device) {
           BluetoothSocket tmp = null;
           mAdapter = BluetoothAdapter.getDefaultAdapter();
           // 获得用于指定蓝牙连接的BluetoothSocket
           try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
           } catch (Exception e) {
                e.printStackTrace();
           }
           mSocket = tmp;

           // 在新线程中建立套接字连接,避免FC
           Thread connectionThread = new Thread(new Runnable() {
                @Override
                public void run() {
                     // TODO Auto-generated method stub
                     // 始终取消发现,因为它会降低连接的速度
                     mAdapter.cancelDiscovery();

                     // 建立到BluetoothSocket的连接
                     try {
                          // 这是一个阻塞调用,只在成功连接或者异常时返回
                          mSocket.connect();
                     } catch (Exception e) {
                          e.printStackTrace();
                          // 设备连接失败,关闭套接字
                          try {
                               mSocket.close();
                          } catch (Exception e2) {
                               // TODO: handle exception
                               e2.printStackTrace();
                          }
                     }
                }
           });

           connectionThread.start();

           InputStream tmpIn = null;
           OutputStream tmpOut = null;

           // 获得BluetoothSoket输入输出流
           try {
                tmpIn = mSocket.getInputStream();
                tmpOut = mSocket.getOutputStream();
                buffer = new byte[1024];
           } catch (Exception e) {
                e.printStackTrace();
           }
           mInStream = tmpIn;
           mOutStream = tmpOut;
      }

      public void run() {
           // 连接时保持监听InputStream
           while (true) {
                try {
                     // 从套接字流读取数据
                     mInStream.read(buffer);
                     // 向UI Activity发送获取的数据
                } catch (Exception e) {
                     // TODO: handle exception
                     // 这里的异常标志着连接的丢失
                     // 向UI Activity发送获取的数据
                     break;
                }
           }
      }
 
      public void write(byte[] buffer)
      {
           try {
                mOutStream.write(buffer);
           } catch (Exception e) {
                e.printStackTrace();
           }
      }
 
      public void cancel()
      {
           try {
                mSocket.close();
           } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
           }
      }
 }

3.监听和接收蓝牙连接请求

在两个蓝牙设备交互之前,其中一个通信设备必须起服务器的作用。它获取一个BluetoothServerSocket实例并监听入站请求。这个实例通过调用蓝牙适配器上的listenUsingRfcommWithServiceRecord()方法获得。有了这个实例我们可以通过start()方法开始监听来自远程设备的入站请求。

  //使主设备处于可发现状态
  Intent disCoverableIntent = new Intent(
                      BluetoothAdapter. ACTION_REQUEST_DISCOVERABLE);
  startActivityForResult(disCoverableIntent,DISCOVERY_REQUEST_BLUETOOTH );

 //创建一个蓝牙服务器并接受连接
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == DISCOVERY_REQUEST_BLUETOOTH ) {
  boolean isDiscoverable = resultCode > 0;
  if (isDiscoverable) {
  // UUID
  // uuid=UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
  final UUID uuid = UUID.randomUUID();
  final String serverName = "BTServer" ;
  final BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
  final BluetoothServerSocket bluetoothServer;
                   Thread listenThread = new Thread(new Runnable() {
  @Override
  public void run() {
  // TODO Auto-generated method stub
  try {
                                  bluetoothServer = bt.listenUsingRfcommWithServiceRecord(serverName, uuid);
                    BluetoothSocket serverSocket = bluetoothServer.accept();
                    myHandleConnectionWiht(serverSocket);
                             } catch (Exception e) {
                                  e.printStackTrace();
                             }
                        }
  private void myHandleConnectionWiht(
                                  BluetoothSocket serverSocket) {
  // TODO Auto-generated method stub
                        }
                   });
                   listenThread.start();
              }
          }
     }

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-07-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.启用蓝牙并使设备处于可发现状态    
  • 2.连接启用蓝牙设备
  • 3.监听和接收蓝牙连接请求
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档