Android Bluetooth Development

Note: Android only supports Bluetooth development from the 2.0 version of the sdk , and the simulator does not support it. At least two mobile phones are required for testing, which restricts the development of many technicians;

 

   First of all, to operate Bluetooth, you must first add permissions to AndroidManifest.xml

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

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

 Then, look at the api. All Android classes related to Bluetooth development are under the android.bluetooth package, as shown in the figure below, there are only 8 classes (the android Chinese API has been uploaded)

                1.jpg
And we need to use only a few:

    1.BluetoothAdapter 

As the name suggests, until we establish a bluetoothSocket connection, there are many ways to continuously operate the Bluetooth adapter. The commonly used methods are as follows:

      cancelDiscovery()  literally cancels discovery, which means that calling this method when we are searching for devices will no longer continue searching

      disable() turns off bluetooth

      enable() turns on bluetooth. This method turns on bluetooth without popping up a prompt. More often, we need to ask the user whether to turn it on. These two lines of code also turn on bluetooth, but the user will be prompted :

Intemtenabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enabler,reCode);//同startActivity(enabler);

      getAddress() gets the local bluetooth address

      getDefaultAdapter() gets the default BluetoothAdapter, in fact, there is only one way to get the BluetoothAdapter

      getName() gets the local bluetooth name

      getRemoteDevice(String address) Get the remote bluetooth device according to the bluetooth address

      getState() gets the current state of the local bluetooth adapter (it may be more necessary when debugging)

      isDiscovering() determines whether the device is currently being found, and returns true

      isEnabled() determines whether Bluetooth is turned on, and returns true if it is turned on, otherwise, returns false

     listenUsingRfcommWithServiceRecord(String name, UUID uuid) Create and return a BluetoothServerSocket based on the name, UUID, which is the first step in creating a BluetoothSocket server

      startDiscovery() starts the search, which is the first step of the search

2.BluetoothDevice

As you can see from the name, this class describes a Bluetooth device

      createRfcommSocketToServiceRecord(UUIDuuid)根据UUID创建并返回一个BluetoothSocket

getState() 蓝牙状态这里要说一下,只有在 BluetoothAdapter.STATE_ON 状态下才可以监听,具体可以看andrid api;

这个方法也是我们获取BluetoothDevice的目的——创建BluetoothSocket
这个类其他的方法,如getAddress(),getName(),同BluetoothAdapter

    3.BluetoothServerSocket

如果去除了Bluetooth相信大家一定再熟悉不过了,既然是Socket,方法就应该都差不多,这个类一种只有三个方法两个重载的accept(),accept(inttimeout)两者的区别在于后面的方法指定了过时时间,需要注意的是,执行这两个方法的时候,直到接收到了客户端的请求(或是过期之后),都会阻塞线程,应该放在新线程里运行!


还有一点需要注意的是,这两个方法都返回一个BluetoothSocket,最后的连接也是服务器端与客户端的两个BluetoothSocket的连接

      close()这个就不用说了吧,翻译一下——关闭!

 4.BluetoothSocket

  跟BluetoothServerSocket相对,是客户端一共5个方法,不出意外,都会用到

      close(),关闭

      connect()连接

      getInptuStream()获取输入流

      getOutputStream()获取输出流

      getRemoteDevice()获取远程设备,这里指的是获取bluetoothSocket指定连接的那个远程蓝牙设备

 

1、获取本地蓝牙适配器

      BluetoothAdapter
mAdapter= BluetoothAdapter.getDefaultAdapter();

 2、打开蓝牙

      if(!mAdapter.isEnabled()){

//弹出对话框提示用户是后打开

Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enabler, REQUEST_ENABLE);

      //不做提示,强行打开

      // mAdapter.enable();

}

3、搜索设备
   1)
刚才说过了mAdapter.startDiscovery()

是第一步,可以你会发现没有返回的蓝牙设备,怎么知道查找到了呢?向下看,不要急。

       使设备能够被搜索

        Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

         startActivityForResult(enabler,REQUEST_DISCOVERABLE); 

2)

定义BroadcastReceiver,关于BroadcastReceiver不多讲了,不是今天的讨论内容,代码如下

  BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //找到设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {

                    Log.v(TAG, "find device:" + device.getName()
                            + device.getAddress());
                }
            }
            //搜索完成
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                setTitle("搜索完成");
                if (mNewDevicesAdapter.getCount() == 0) {
                    Log.v(TAG, "find over");
                }
            }
        }
    };

 这样,没当查找到新设备或是搜索完成,相应的操作都在上段代码的两个if里执行了,不过前提是你要先注册

 

BroadcastReceiver,具体代码如下

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(mReceiver, filter)<span style="font-family:SimSun;">;</span>


(这段代码,一般写在onCreate()里..)

  4、建立连接,首先Android sdk(2.0以上版本)支持的蓝牙连接是通过BluetoothSocket建立连接(说的不对请高人指正),服务器端(BluetoothServerSocket)和客户端(BluetoothSocket)需指定同样的UUID,才能建立连接,因为建立连接的方法会阻塞线程,所以服务器端和客户端都应启动新线程连接:

 

 

1)服务器端:


//UUID
格式一般是"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"可到

        //http://www.uuidgenerator.com 申请


BluetoothServerSocket serverSocket = mAdapter. listenUsingRfcommWithServiceRecord(serverSocketName,UUID);
serverSocket.accept();


2)
客户端:
//
还记得我们刚才在BroadcastReceiver获取了BLuetoothDevice么?
BluetoothSocket clienSocket=dcvice. createRfcommSocketToServiceRecord(UUID);
clienSocket.connect();


5
、数据传递,通过以上操作,就已经建立的BluetoothSocket连接了,数据传递无非是通过流的形式
1
)获取流
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();

2)写出、读入
这是基础的东西,在这就不多赘述了
终于写完了,这是我这两天的学习经验,希望对有蓝牙需求的朋友有所帮助!另外,之前我们提过

There are 8 classes under android.bluetooth , and 4 classes are not used. Those 4 classes define constants, which are not commonly used.

Finally: Here is an official example, including server and client:
http://download.csdn.net/detail/q610098308/8628675

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326669195&siteId=291194637