Introduction to Android Bluetooth development

Source: Internet
Author: User
Tags connect socket

Android Bluetooth system

Bluetooth is a radio technology that supports short-range communication (typically 10m), which allows wireless information exchange between a wide variety of devices.

Bluetooth modules in the Android system

Android includes support for the Bluetooth network protocol stack, enabling Bluetooth devices to wirelessly connect to other Bluetooth devices to exchange data.

By using the Bluetooth API, an Android application can achieve the following functions:
-Scan other Bluetooth devices
-Query local Bluetooth adapter for pairing Bluetooth device
-Establish RFCOMM Channel
-Connect other devices via service discovery
-Data communication
-Manage multiple connections

From top to bottom, Bluetooth systems in the Android platform include Bluetooth classes, Android adaptation libraries, BlueZ libraries, drivers, and protocols in the Java framework.

The source code in the Bluetooth module
    • Initializing the Bluetooth chip

      通过BlueZ工具hciattach进行的,命令格式如下:    hciattach [-n] [-p] [-b] [-t timeout] [-s initial_speed] <tty> <type | id> [speed] [flow|noflow] [bdaddr]type决定了要初始化的设备的型号,可以使用hciattach -1来列出所支持的设备型号。Hciattach命令内部的工作步骤是:首先打开制定的tty设备,再做一些通用的设置,如flow等, 之后设置波特率为initial_speed,然后根据type调用各自的初始化代码,最后将波特率重新设置为speed。
    • Bluetooth service

      一般不需要自己定义,只需要使用初始化脚本文件init.rc中的默认内容即可。
    • Manage Bluetooth power

      可以调用rfkill接口来控制电源管理,如果已经实现了rfkill接口,则无需再进行配置。
Bluetooth-related class Bluetoothsocket class
    • Bluetoothsocket Class Basics

      Android's Bluetooth system and socket sockets are closely related, the Bluetooth side of the listening interface and TCP port similar, are using the socket and the ServerSocket class. Use the Bluetoothserversocket class on the server side to create a listening service port. When a connection is accepted by Bluetoothserversocket, it returns a new bluetoothsocket to manage the connection. On the client side, use a separate Bluetoothsocket class to initialize an external connection and manage the connection.

      The most commonly used Bluetooth port is Rfcomm, which is a connection-oriented, data stream transmission via a Bluetooth module, also known as the serial Port specification (SPP).

      Create a bluetoothsocket to connect to a known device, using Method Bluetoothdevice.createrfcommsockettoservicerecord (). Then call the Connect () method to try a connection for the remote device. This call will be blocked to instruct a connection to be established or the link to fail.

      When the port connection succeeds, the I/O stream is opened by getInputStream () and Getoutputstream () to obtain the respective InputStream and OutputStream objects.

      The thread of the Bluetoothsocket class is secure, because the close () method immediately discards the external operation and shuts down the server port.

    • Public methods of the Bluetoothsocket class

      • public void Close ()
      • public void Connect ()
      • Public InputStream getInputStream ()
      • Public OutputStream Getoutputstream ()
      • Public Bluetoothdevice Getremotedevice ()
Bluetoothserversocket class
    • Public methods of the Bluetoothserversocket class

      • Public Bluetoothsocket Accept (int timeout)
      • Public Bluetoothsocket Accept ()
      • public void Close ()
Bluetoothadapter class
  • Bluetoothadapter Class Basics

    Represents a local Bluetooth adapter device that allows users to perform basic Bluetooth tasks such as initializing a device's search, querying a matching set of devices, using a known MAC address to initialize a Bluetoothdevice class, Create a Bluetoothserversocket class to listen for other device connection requests to this machine, and so on.

    Call the static method Getdefaultadapter (), which is the first step for all Bluetooth actions to be used. When the local adapter is available, the user can obtain a series of Bluetoothdevice objects representing all the matched devices that have the Getbondeddevice () method, and the StartDiscovery () method to start the device search , or create a Bluetoothserversocket class that listens for new connection requests through the Listenusingrfcommwithservicerecord (String,uuid) method.

    Most methods require Bluetooth permissions, and some methods require Bluetooth_admin permissions at the same time.

  • Constants of the Bluetoothadapter class

    • String action_discovery_finished

      广播事件:本地蓝牙适配器已经完成设备的搜索过程,需要BLUETOOTH权限接收。常量值:android.bluetooth.adapter.action.DISCOVERY_FINISHED
    • String action_discovery_started

      广播事件:本地蓝牙适配器已经开始对远程设备的搜寻过程。用户可以通过cancelDiscovery()类来取消正在执行的查找过程,需要BLUETOOTH权限接收。常量值:android.bluetooth.adapter.action.DISCOVERY_STARTED
    • String action_local_name_changed

      广播事件:本地蓝牙适配器已经更改了它的蓝牙名称,需要BLUETOOTH权限接收。常量值:android.bluetooth.adapter.action.LOCAL_NAME_CHANGED
    • String action_request_discoverable

      Activity活动:显示一个请求被搜寻模式的系统活动。Android运用onActivityResult(int,int,Intent)回收方法来传递该活动结果的通知。需要BLUETOOTH权限。常量值:android.bluetooth.adapter.action.REQUEST_DISCOVERYABLE
    • String action_request_enable

      Activity活动:显示一个允许用户打开蓝牙模块的系统活动。Android运用onActivityResult(int,int,Intent)回收方法来传递该活动结果的通知。需要BLUETOOTH权限。常量值:android.bluetooth.adapte.action.REQUEST_ENABLE
    • String action_scan_mode_changed

      广播活动:指明蓝牙扫描模块或者本地适配器已经发生变化,需要BLUETOOTH权限。常量值:android.bluetooth.adapter.action.SCAN_MODE_CHANGED
    • String action_state_changed

      广播活动:本来的蓝牙适配器的状态已经改变,如蓝牙模块已经被打开或者关闭,需要BLUETOOTH权限接收。常量值:android.bluetooth.adapter.action.STATE_CHANGED
    • int ERROR

      功能:标记该类的错误值,确保和该类中的任意其他整数常量不相等。它为需要一个标记错误值的函数提供了便利,例如:Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.ERROR);
    • String extra_discoverable_duration

      功能:试图在ACTION_REQUEST_DISCOVERABLE常量中作为一个可选的整型附加域,来为短时间内的设备发现请求一个特定的持续时间,默认值为120秒,超过300秒的请求将被限制。常量值:android.bluetooth.adapter.extra.DISCOVERABLE_DURATION
    • String Extra_local_name

      功能:试图在ACTION_LOCAL_NAME_CHANGED常量中作为一个字符串附加域,来请求本地蓝牙的名称。常量值:android.bluetooth.adapter.extra.LOCAL_NAME
    • String Extra_previous_scan_mode

      功能:试图在ACTION_SCAN_MODE_CHANGED常量中作为一个整型附加域,来请求以前的扫描模式,可能值如下:    SCAN_MODE_NONE    SCAN_MODE_CONNECTABLE    SCAN_MODE_CONNECTABLE_DISCOVERABLE常量值:android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE
    • String extra_previous_state

      功能:试图在ACTION_STATE_CHANGED常量中作为一个整型附加域,来请求以前的供电状态。可能值如下:    STATE_OFF    STATE_TURNING_ON    STATE_ON    STATE_TURNING_OFF常量:android.bluetooth.adapter.extra.PREVIOUS_STATE
    • String Extra_scan_mode

      功能:试图在ACTION_SCAN_MODE_CHANGED常量作为一个整型附加域,来请求当前的扫描模式,可能值如下:    SCAN_MODE_NONE    SCAN_MODE_CONNECTABLE    SCAN_MODE_CONNECTABLE_DISCOVERABLE常量值:android.bluetooth.adapter.extra.SCAN_MODE
    • String extra_state

      功能:试图在ACTION_STATE_CHANGED常量中作为一个整型附加域,来请求当前供电状态,可能值如下:    STATE_OFF    STATE_TURNING_ON    STATE_ON    STATE_TURNING_OFF常量值:android.bluetooth.adapter.extra.STATE
    • int scan_mode_connectable

      功能:指明在本地蓝牙适配器中,查询扫描功能失效,但页面扫描功能有效。因此,该设备不能被远程蓝牙设备发现,但如果以前曾经发现过该设备,则远程设备可以对其进行连接。常量值:21(0x00000015)
    • int scan_mode_connectable_discoverable

      功能:指明在本地蓝牙适配器中, 查询扫描功能都有效,因此,该设备既可以被远程蓝牙设备发现,也可以被其连接。常量值:23(0x00000017)
    • int Scan_mode_none

      功能:指明在本地蓝牙适配器中,查询扫描功能和页面扫描功能都失效,因此,该设备既不可以被远程蓝牙设备发现,也不可以被连接。常量值:20(0x00000014)
    • int State_off

      功能:指明本地蓝牙适配器模式已经关闭常量值:10(0x0000000a)
    • int state_on

      功能:指明本地蓝牙适配器模块已经打开,并且准备被使用
    • int State_turning_off

      功能:指明本地蓝牙适配器模块正在关闭。本地客户端可以立刻尝试友好地断开任意外部连接。常量值:13(0x0000000d)
    • int state_turning_on

      功能:指明本地蓝牙适配器模块正在打开,然而本地客户在尝试使用这个适配器之前需要为STATE_ON状态而等待常量值:11(0x000000b)
  • Public methods of the Bluetoothadapter class

    • public boolean canceldiscovery ()
    • public static Boolean checkbluetoothaddress (String address)
    • public boolean disable ()
    • public boolean enable ()
    • Public String getaddress ()
    • Public Set getbondeddevices ()
    • public static synchronized Bluetoothadapter Getdefaultadapter ()
    • Public String GetName ()
    • Public Bluetoothdevice Getremotedevice (String address)
    • public int Getscanmode ()
    • public int getState ()
    • public boolean isdiscovering ()
    • public boolean isenabled ()
    • Public Bluetoothserversocket Listenusingrfcommwithservicerecord (String name,uuid UUID)
    • public boolean setName (String name)
    • public boolean startdiscovery ()
Bluetoothclass.service class

Used to define all service class constants, any bluetoothclass consists of 0 or more service class encodings. The following constants are included in the class Bluetoothclass.service:

    • int AUDIO
    • int CAPTURE
    • int information
    • int limited_discoverability
    • int NETWORKING
    • int Object_transfer
    • int positioning
    • int RENDER
    • int TELEPHONY
Bluetoothclass.device class

Constants used to define all device classes, each bluetoothclass has a device class with a primary and a smaller part encoded, and the constants represent a combination of the main and smaller device class parts (the complete device Class).

Developing Bluetooth apps on the Android platform
  • 1. Set permissions

    <uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  • 2. Activate Bluetooth

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if(mBluetoothAdapter == null){    //表示手机不支持蓝牙    return;}if(!mBluetoothAdapter.isEnabled()){ //蓝牙未开启,则开启蓝牙    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    startActivityForResult(enableIntent,REQUEST_ENABLE_BT);}//...public void onActivityResult(int requestCode,int resultCode,Intent data){    if(requestCode == REQUEST_ENABLE_BT){        if(resultCode == RESULT_OK){            //蓝牙已经开启        }    }}
  • 3. Discover Bluetooth devices

    Make native Bluetooth searchable within 300 seconds private void ensurediscoverable () {if (Mbluethadapter.getscanmode ()! = Bluetoothadapter.scan_mode_         connectable_discoverable) {Intent discoverableintent = new Intent (bluetoothadapter.ation_request_discoverable);        Intent.putextra (bluetoothadapter.extra_discoverable_duration,300);    StartActivity (discoverableintent); }}//find a paired Bluetooth device, which is a previously paired device set<bluetoothdevice> paireddevices = Mbluetoothadapter.getbondeddevices ();    Paireddevices.size () > 0) {Findviewbyid (r.id.title_paired_devices). setvisibility (view.visible);    for (Bluetoothdevice device:paireddevices) {//device.getname () + "" + device.getaddress (); }}else{Mpaireddevicesarrayadapter.add ("No matching device Found");} Register when a device is found to call onreceiveintentfilter filter = new Intentfilter (bluetoothdevice.action_found); This.registerreceiver (mreceiver,filter);//When the search is complete, call Onreceivefilter = new Intentfilter (bluetoothadapter.action_ discovery_finished); This.registerreceiver (mreceiver,filter);//...pRivate broadcastreceiver mreceiver = new Broadcastreceiver () {@Override public void Onreceiver (Context context,inten        T intent) {String action = intent.getaction (); if (BluetoothDevice.ACTION_FOUND.equal (ACTION)) {Bluetoothdevice device = Intent.getparcelableextra (Bluetoothdev Ice.            Extra_device); If it is already paired, skip if (device.getbondstate ()! = bluetoothdevice.bond_bonded) {Mnewdevicesarrayadapter.add             (Device.getname () + "\ n" +device.getaddress ()); }}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equal (ACTION)) {//Search ends if (mnewdevicesar            Rayadapter.getcount () = = 0) {mnewdevicesarrayadapter.add ("No Search to Device"); }        }    }}
  • 4. Establish a connection

    The UUID can be seen as a port number private static final UUID My_uuid = uuid.fromstring ("Fa87c0d0-afac-11de-8a39-0800200c9a66");//    Like a server at all times to listen to whether there is a connection to establish private class Acceptthread extend thread{private bluetoothserversocket serversocket;        Public Acceptthread (Boolean secure) {Bluetoothserversocket temp = null;        try{temp = Mbluetoothadapter.listenusingrfcommwithservicerecord (NAME_INSECURE,MY_UUID);        }catch (IOException e) {log.e ("TAG", "Listen () failed" +e);    } serversocket = temp;        public void Run () {bluetoothsocket socket = null;            while (true) {try{socket = serversocket.accept ();                }catch (IOException e) {log.e ("TAG", "Accept () failed" +e);            Break }} if (socket! = NULL) {//can create a new data interchange thread at this time, pass this socket in}}//Cancel listening public void cance        L () {try{serversocket.close (); }catch () {LOG.E ("TAG", "SocKet Type "+sockettype+" close () of server failed "+e); }    }}
  • 5. Exchanging data

    Another device to connect to the machine, equivalent to the client private class Connectthread extends thread{private bluetoothsocket socket;    private Bluetoothdevice device;        Public Connectthread (Bluetoothdevice Device,boolean secure) {this.device = device;        Bluetoothsocket tmp = NULL;        try{tmp = Device.createrfcommsockettoservicerecord (my_uuid_secure);        }catch (IOException e) {log.e ("TAG", "Create () failed" +e);         }} public void Run () {mbluetoothadapter.canceldiscovery ();//Cancel Device lookup try{socket.connect ();            }catch (IOException e) {try{socket.close ();            }catch (IOException E1) {log.e ("TAG", "unable to close" + "socket during connection failure" +e1); } connectionfailed ();        Connection failed return;        }//At this point you can create a new data interchange thread, pass this socket in} public void Cancel () {try{socket.close (); }catch () {LOG.E ("TAG", "Close () of the Connect SocKet failed "+e); }    }}
  • 6. Establish a data communication thread

    After establishing the connection, the thread for data communication is private class Connectedthread extend thread{private bluetoothsocket socket;    Private InputStream instream;    Private OutputStream OutStream;        Public Connectedthread (Bluetoothsocket socket) {this.socket = socket;            try{//Get input/output stream instream = Socket.getinpustream ();        OutStream = Socket.getoutputstream ();        }catch (IOException e) {log.e ("TAG", "temp sockets not created" +e);        }} public void Run () {byte[] buff = new byte[1024];        int len = 0;                Read data need to be constantly listening, write does not need while (true) {try{len = instream.read (buff);            Sends the read data to the UI for display Message msg = handler.obtainmessage (Bluetoothchat.message_read,len,-1,buff);                }catch (IOException e) {log.e ("TAG", "Disconnected" +e); Connectionlost (); Lost connection start ();            Restart server break; }}} public void Write (byte[] buffer) {try{outstream.write (buffer);            Handler.obtainmessage (Bluetoothchat.message_write,-1,-1,buffer);        Msg.sendtotarget ();        }catch (IOException e) {log.e ("TAG", "Exception during write" +e);        }} public void Cancel () {try{socket.close ();        }catch (IOException e) {log.e ("TAG", "Close () of Connect socket failed" +e); }    }}

Introduction to Android Bluetooth development

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.