• Android之蓝牙设备使用


    1. 首先需要在AndroidManifest.xml中导入以下权限:
    <uses-permissionandroid:name="android.permission.BLUETOOTH"/>
    <uses-permissionandroid:name="android.permission. BLUETOOTH_ADMIN "/>
     


    2. 把你手机的蓝牙设置设置为可用状态,这里有两步:
    A.  获得BluetoothAdapter,如果返回值为null,说明设备不支持蓝牙
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
       
    // Device does not support Bluetooth
    }

    B. 打开蓝牙设备驱动,BluetoothAdapter.ACTION_REQUEST_ENABLE  打开一个对话框进行选择
    if (!mBluetoothAdapter.isEnabled()) {
       
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult
    (enableBtIntent, REQUEST_ENABLE_BT);
    }



    3. 寻找蓝牙设备

    A. 首先获取已配对的远端设备,并把设备的名字以及地址添加到adapter
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    // If there are paired devices
    if (pairedDevices.size() > 0) {
       
    // Loop through paired devices
       
    for (BluetoothDevice device : pairedDevices) {
           
    // Add the name and address to an array adapter to show in a ListView
            mArrayAdapter
    .add(device.getName() + "\n" + device.getAddress());
       
    }
    }
    B. 然后通过BluetoothAdapter.startDiscovery启动蓝牙设备的搜索备,注意:这是一个异步方法,调用的时候立刻就会返回。为了获得搜寻的结果,必须在用户自己的Activity中注册一个BroadcastReceiver
    // Create a BroadcastReceiver for ACTION_FOUND
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
       
    public void onReceive(Context context, Intent intent) {
           
    String action = intent.getAction();
           
    // When discovery finds a device
           
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
               
    // Get the BluetoothDevice object from the Intent
               
    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
               
    // Add the name and address to an array adapter to show in a ListView
                mArrayAdapter
    .add(device.getName() + "\n" + device.getAddress());
           
    }
       
    }
    };
    // Register the BroadcastReceiver
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver
    (mReceiver, filter); // Don't forget to unregister during onDestroy
    C. 使你的设备能够被其他设备搜索到
    Intent discoverableIntent = new
    Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent
    .putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
    startActivity
    (discoverableIntent);


    4. 连接设备
    A. 作为连接方的服务器
    private class AcceptThread extends Thread {
       
    private final BluetoothServerSocket mmServerSocket;
     
       
    public AcceptThread() {
           
    // Use a temporary object that is later assigned to mmServerSocket,
           
    // because mmServerSocket is final
           
    BluetoothServerSocket tmp = null;
           
    try {
               
    // MY_UUID is the app's UUID string, also used by the client code
                tmp
    = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
           
    } catch (IOException e) { }
            mmServerSocket
    = tmp;
       
    }
     
       
    public void run() {
           
    BluetoothSocket socket = null;
           
    // Keep listening until exception occurs or a socket is returned
           
    while (true) {
               
    try {
                    socket
    = mmServerSocket.accept();
               
    } catch (IOException e) {
                   
    break;
               
    }
               
    // If a connection was accepted
               
    if (socket != null) {
                   
    // Do work to manage the connection (in a separate thread)
                    manageConnectedSocket
    (socket);
                    mmServerSocket
    .close();
                   
    break;
               
    }
           
    }
       
    }
     
       
    /** Will cancel the listening socket, and cause the thread to finish */
       
    public void cancel() {
           
    try {
                mmServerSocket
    .close();
           
    } catch (IOException e) { }
       
    }
    }
    B. 作为连接方的客户端
    private class ConnectThread extends Thread {
       
    private final BluetoothSocket mmSocket;
       
    private final BluetoothDevice mmDevice;
     
       
    public ConnectThread(BluetoothDevice device) {
           
    // Use a temporary object that is later assigned to mmSocket,
           
    // because mmSocket is final
           
    BluetoothSocket tmp = null;
            mmDevice
    = device;
     
           
    // Get a BluetoothSocket to connect with the given BluetoothDevice
           
    try {
               
    // MY_UUID is the app's UUID string, also used by the server code
                tmp
    = device.createRfcommSocketToServiceRecord(MY_UUID);
           
    } catch (IOException e) { }
            mmSocket
    = tmp;
       
    }
     
       
    public void run() {
           
    // Cancel discovery because it will slow down the connection
            mBluetoothAdapter
    .cancelDiscovery();
     
           
    try {
               
    // Connect the device through the socket. This will block
               
    // until it succeeds or throws an exception
                mmSocket
    .connect();
           
    } catch (IOException connectException) {
               
    // Unable to connect; close the socket and get out
               
    try {
                    mmSocket
    .close();
               
    } catch (IOException closeException) { }
               
    return;
           
    }
     
           
    // Do work to manage the connection (in a separate thread)
            manageConnectedSocket
    (mmSocket);
       
    }
     
       
    /** Will cancel an in-progress connection, and close the socket */
       
    public void cancel() {
           
    try {
                mmSocket
    .close();
           
    } catch (IOException e) { }
       
    }
    }
    5. 设备连接时候的数据传输
    private class ConnectedThread extends Thread {
       
    private final BluetoothSocket mmSocket;
       
    private final InputStream mmInStream;
       
    private final OutputStream mmOutStream;
     
       
    public ConnectedThread(BluetoothSocket socket) {
            mmSocket
    = socket;
           
    InputStream tmpIn = null;
           
    OutputStream tmpOut = null;
     
           
    // Get the input and output streams, using temp objects because
           
    // member streams are final
           
    try {
                tmpIn
    = socket.getInputStream();
                tmpOut
    = socket.getOutputStream();
           
    } catch (IOException e) { }
     
            mmInStream
    = tmpIn;
            mmOutStream
    = tmpOut;
       
    }
     
       
    public void run() {
           
    byte[] buffer = new byte[1024];  // buffer store for the stream
           
    int bytes; // bytes returned from read()
     
           
    // Keep listening to the InputStream until an exception occurs
           
    while (true) {
               
    try {
                   
    // Read from the InputStream
                    bytes
    = mmInStream.read(buffer);
                   
    // Send the obtained bytes to the UI activity
                    mHandler
    .obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                           
    .sendToTarget();
               
    } catch (IOException e) {
                   
    break;
               
    }
           
    }
       
    }
     
       
    /* Call this from the main activity to send data to the remote device */
       
    public void write(byte[] bytes) {
           
    try {
                mmOutStream
    .write(bytes);
           
    } catch (IOException e) { }
       
    }
     
       
    /* Call this from the main activity to shutdown the connection */
       
    public void cancel() {
           
    try {
                mmSocket
    .close();
           
    } catch (IOException e) { }
       
    }
    }

  • 相关阅读:
    一种开源的分布式消息系统Nats
    资产盘点:除了金钱,一个人还有哪些资产?
    博客首页规则改版公告
    <html>
    欢迎使用CSDN-markdown编辑器
    java 小程序查看器 启动:未初始化小程序 解决方法
    Hadoop2.6.0版本号MapReudce演示样例之WordCount(一)
    深入学习IOZone【转】
    i.MX6UL -- PWM用户空间使用方法【转】
    linux PWM蜂鸣器移植以及驱动程序分析【转】
  • 原文地址:https://www.cnblogs.com/lee0oo0/p/2618522.html
Copyright © 2020-2023  润新知