1. 程式人生 > >Android BLE與終端通信(三)——client與服務端通信過程以及實現數據通信

Android BLE與終端通信(三)——client與服務端通信過程以及實現數據通信

.sh 沒有 indexof 實例 解析 rip listview filter @override

Android BLE與終端通信(三)——client與服務端通信過程以及實現數據通信


前面的終究僅僅是小知識點。上不了臺面,也僅僅能算是起到一個科普的作用。而同步到實際的開發上去,今天就來延續前兩篇實現藍牙主從關系的client和服務端了。本文相關鏈接須要去google的API上查看,須要FQ的

Bluetooth Low Energy:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html

可是我們依舊沒有講到BLE(低功耗藍牙)。放心,下一篇就回講到。跟前面的基本上非常大的不同,我們今天來看下client和服務端的實現

我們以上篇為栗子:
Android BLE與終端通信(二)——Android Bluetooth基礎搜索藍牙設備顯示列表

一.藍牙傳輸數據

藍牙傳輸數據事實上跟我們的 Socket(套接字)有點相似。假設有不懂的。能夠百度一下概念,我們僅僅要知道是這麽回事就能夠了,在網絡中使用Socket和ServerSocket控制client和服務端來數據讀寫。而藍牙通訊也是由client和服務端來完畢的,藍牙clientSocket是BluetoothSocket,藍牙服務端Socket是BluetoothServerSocket,這兩個類都在android.bluetooth包下。並且不管是BluetoothSocket還是BluetoothServerSocket,我們都須要一個UUID(標識符),這個UUID在上篇也是有提到,並且他的格式也是固定的:

UUID:XXXXXXXX(8)-XXXX(4)-XXXX(4)-XXXX(4)-XXXXXXXXXXXX(12)

第一段是8位,中間三段式4位,最後一段是12位。UUID相當於Socket的端口。而藍牙地址則相當於Socket的IP

1.activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical" >
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="btnSearch" android:text="搜索藍牙設備" /> <ListView android:id="@+id/lvDevices" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> </LinearLayout>

2.實現步驟

1.聲明

我們須要的東西
  // 本地藍牙適配器
    private BluetoothAdapter mBluetoothAdapter;
    // 列表
    private ListView lvDevices;
    // 存儲搜索到的藍牙
    private List<String> bluetoothDevices = new ArrayList<String>();
    // listview的adapter
    private ArrayAdapter<String> arrayAdapter;
    // UUID.randomUUID()隨機獲取UUID
    private final UUID MY_UUID = UUID
     .fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");
    // 連接對象的名稱
    private final String NAME = "LGL";
    // 這裏本身即是服務端也是client,須要例如以下類
    private BluetoothSocket clientSocket;
    private BluetoothDevice device;
    // 輸出流_client須要往服務端輸出
    private OutputStream os;

2.初始化

// 獲取本地藍牙適配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 推斷手機是否支持藍牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "設備不支持藍牙", Toast.LENGTH_SHORT).show();
            finish();
        }

        // 推斷是否打開藍牙
        if (!mBluetoothAdapter.isEnabled()) {
            // 彈出對話框提示用戶是後打開
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 1);
            // 不做提示,強行打開
            // mBluetoothAdapter.enable();
        }
        // 初始化listview
        lvDevices = (ListView) findViewById(R.id.lvDevices);
        lvDevices.setOnItemClickListener(this);

        // 獲取已經配對的設備
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
                .getBondedDevices();

        // 推斷是否有配對過的設備
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                // 遍歷到列表中
                bluetoothDevices.add(device.getName() + ":"
                        + device.getAddress() + "\n");
            }
        }

        // adapter
        arrayAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                bluetoothDevices);
        lvDevices.setAdapter(arrayAdapter);

        /**
         * 異步搜索藍牙設備——廣播接收
         */
        // 找到設備的廣播
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        // 註冊廣播
        registerReceiver(receiver, filter);
        // 搜索完畢的廣播
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        // 註冊廣播
        registerReceiver(receiver, filter);
    }

3.點擊搜索

public void btnSearch(View v) {
        // 設置進度條
        setProgressBarIndeterminateVisibility(true);
        setTitle("正在搜索...");
        // 推斷是否在搜索,假設在搜索,就取消搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // 開始搜索
        mBluetoothAdapter.startDiscovery();
    }

4.搜索設備

private final BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 收到的廣播類型
            String action = intent.getAction();
            // 發現設備的廣播
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 從intent中獲取設備
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 推斷是否配對過
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    // 加入到列表
                    bluetoothDevices.add(device.getName() + ":"
                            + device.getAddress() + "\n");
                    arrayAdapter.notifyDataSetChanged();

                }
                // 搜索完畢
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                // 關閉進度條
                setProgressBarIndeterminateVisibility(true);
                setTitle("搜索完畢!");
            }
        }
    };

5.client實現已經發送數據流


    // client
    @Override
    public void onItemClick(AdapterView<?

> parent, View view, int position, long id) { // 先獲得藍牙的地址和設備名 String s = arrayAdapter.getItem(position); // 單獨解析地址 String address = s.substring(s.indexOf(":") + 1).trim(); // 主動連接藍牙 try { // 推斷是否在搜索,假設在搜索,就取消搜索 if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } try { // 推斷能否夠獲得 if (device == null) { // 獲得遠程設備 device = mBluetoothAdapter.getRemoteDevice(address); } // 開始連接 if (clientSocket == null) { clientSocket = device .createRfcommSocketToServiceRecord(MY_UUID); // 連接 clientSocket.connect(); // 獲得輸出流 os = clientSocket.getOutputStream(); } } catch (Exception e) { // TODO: handle exception } // 假設成功獲得輸出流 if (os != null) { os.write("Hello Bluetooth!".getBytes("utf-8")); } } catch (Exception e) { // TODO: handle exception } }

6.Handler服務

// 服務端,須要監聽client的線程類
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(MainActivity.this, String.valueOf(msg.obj),
                    Toast.LENGTH_SHORT).show();
            super.handleMessage(msg);
        }
    };

7.服務端讀取數據流

// 線程服務類
    private class AcceptThread extends Thread {
        private BluetoothServerSocket serverSocket;
        private BluetoothSocket socket;
        // 輸入 輸出流
        private OutputStream os;
        private InputStream is;

        public AcceptThread() {
            try {
                serverSocket = mBluetoothAdapter
                        .listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            // 截獲client的藍牙消息
            try {
                socket = serverSocket.accept(); // 假設堵塞了。就會一直停留在這裏
                is = socket.getInputStream();
                os = socket.getOutputStream();
                // 不斷接收請求,假設client沒有發送的話還是會堵塞
                while (true) {
                    // 每次僅僅發送128個字節
                    byte[] buffer = new byte[128];
                    // 讀取
                    int count = is.read();
                    // 假設讀取到了,我們就發送剛才的那個Toast
                    Message msg = new Message();
                    msg.obj = new String(buffer, 0, count, "utf-8");
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

8.開啟服務

首先要聲明
        //啟動服務
        ac = new AcceptThread();
        ac.start();

MainActivity完整代碼

package com.lgl.bluetoothget;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener {

    // 本地藍牙適配器
    private BluetoothAdapter mBluetoothAdapter;
    // 列表
    private ListView lvDevices;
    // 存儲搜索到的藍牙
    private List<String> bluetoothDevices = new ArrayList<String>();
    // listview的adapter
    private ArrayAdapter<String> arrayAdapter;
    // UUID.randomUUID()隨機獲取UUID
    private final UUID MY_UUID = UUID
     .fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");
    // 連接對象的名稱
    private final String NAME = "LGL";

    // 這裏本身即是服務端也是client,須要例如以下類
    private BluetoothSocket clientSocket;
    private BluetoothDevice device;
    // 輸出流_client須要往服務端輸出
    private OutputStream os;
    //線程類的實例
    private AcceptThread ac;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {

        // 獲取本地藍牙適配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 推斷手機是否支持藍牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "設備不支持藍牙", Toast.LENGTH_SHORT).show();
            finish();
        }

        // 推斷是否打開藍牙
        if (!mBluetoothAdapter.isEnabled()) {
            // 彈出對話框提示用戶是後打開
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 1);
            // 不做提示。強行打開
            // mBluetoothAdapter.enable();
        }
        // 初始化listview
        lvDevices = (ListView) findViewById(R.id.lvDevices);
        lvDevices.setOnItemClickListener(this);

        // 獲取已經配對的設備
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
                .getBondedDevices();

        // 推斷是否有配對過的設備
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                // 遍歷到列表中
                bluetoothDevices.add(device.getName() + ":"
                        + device.getAddress() + "\n");
            }
        }

        // adapter
        arrayAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                bluetoothDevices);
        lvDevices.setAdapter(arrayAdapter);

        //啟動服務
        ac = new AcceptThread();
        ac.start();

        /**
         * 異步搜索藍牙設備——廣播接收
         */
        // 找到設備的廣播
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        // 註冊廣播
        registerReceiver(receiver, filter);
        // 搜索完畢的廣播
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        // 註冊廣播
        registerReceiver(receiver, filter);
    }

    public void btnSearch(View v) {
        // 設置進度條
        setProgressBarIndeterminateVisibility(true);
        setTitle("正在搜索...");
        // 推斷是否在搜索,假設在搜索。就取消搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // 開始搜索
        mBluetoothAdapter.startDiscovery();
    }

    // 廣播接收器
    private final BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 收到的廣播類型
            String action = intent.getAction();
            // 發現設備的廣播
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 從intent中獲取設備
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 推斷是否配對過
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    // 加入到列表
                    bluetoothDevices.add(device.getName() + ":"
                            + device.getAddress() + "\n");
                    arrayAdapter.notifyDataSetChanged();

                }
                // 搜索完畢
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                // 關閉進度條
                setProgressBarIndeterminateVisibility(true);
                setTitle("搜索完畢!");
            }
        }
    };

    // client
    @Override
    public void onItemClick(AdapterView<?

> parent, View view, int position, long id) { // 先獲得藍牙的地址和設備名 String s = arrayAdapter.getItem(position); // 單獨解析地址 String address = s.substring(s.indexOf(":") + 1).trim(); // 主動連接藍牙 try { // 推斷是否在搜索,假設在搜索,就取消搜索 if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } try { // 推斷能否夠獲得 if (device == null) { // 獲得遠程設備 device = mBluetoothAdapter.getRemoteDevice(address); } // 開始連接 if (clientSocket == null) { clientSocket = device .createRfcommSocketToServiceRecord(MY_UUID); // 連接 clientSocket.connect(); // 獲得輸出流 os = clientSocket.getOutputStream(); } } catch (Exception e) { // TODO: handle exception } // 假設成功獲得輸出流 if (os != null) { os.write("Hello Bluetooth!".getBytes("utf-8")); } } catch (Exception e) { // TODO: handle exception } } // 服務端。須要監聽client的線程類 private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { Toast.makeText(MainActivity.this, String.valueOf(msg.obj), Toast.LENGTH_SHORT).show(); super.handleMessage(msg); } }; // 線程服務類 private class AcceptThread extends Thread { private BluetoothServerSocket serverSocket; private BluetoothSocket socket; // 輸入 輸出流 private OutputStream os; private InputStream is; public AcceptThread() { try { serverSocket = mBluetoothAdapter .listenUsingRfcommWithServiceRecord(NAME, MY_UUID); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run() { // 截獲client的藍牙消息 try { socket = serverSocket.accept(); // 假設堵塞了。就會一直停留在這裏 is = socket.getInputStream(); os = socket.getOutputStream(); // 不斷接收請求,假設client沒有發送的話還是會堵塞 while (true) { // 每次僅僅發送128個字節 byte[] buffer = new byte[128]; // 讀取 int count = is.read(); // 假設讀取到了,我們就發送剛才的那個Toast Message msg = new Message(); msg.obj = new String(buffer, 0, count, "utf-8"); handler.sendMessage(msg); } } catch (Exception e) { // TODO: handle exception } } } }

Google的API上事實上已經說的非常具體了的,這裏我再提供一份PDF學習文檔,能夠更加直觀的了解

PDF文檔下載地址:http://download.csdn.net/detail/qq_26787115/9416162

Demo下載地址:http://download.csdn.net/detail/qq_26787115/9416158

Android BLE與終端通信(三)——client與服務端通信過程以及實現數據通信