Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 藍牙通信實戰:客戶端與伺服器端的完整建構

編輯:關於 Android 程式設計

前言

先說一件很重要的事:藍牙功能必須用真機測試。模擬器沒有相關硬體,一定會報錯。以下是最後的執行結果:


一、基礎 API 概覽

1. 判斷裝置是否支援藍牙

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
    // 不支援藍牙
} else {
    // 支援藍牙
}

2. 要求使用者開啟藍牙

if (!bluetoothAdapter.isEnabled()) {
    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}

3. 監聽藍牙開關狀態

BroadcastReceiver bluetoothState = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
        switch (state) {
            case BluetoothAdapter.STATE_TURNING_ON:  break;
            case BluetoothAdapter.STATE_ON:          break;
            case BluetoothAdapter.STATE_TURNING_OFF: break;
            case BluetoothAdapter.STATE_OFF:         break;
        }
    }
};
registerReceiver(bluetoothState, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

4. 讓本機可被搜尋

Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(discoveryIntent, REQUEST_DISCOVERY);

BroadcastReceiver discovery = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, -1);
        int preScanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, -1);
    }
};
registerReceiver(discovery, new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));

5. 搜尋裝置

開始搜尋:bluetoothAdapter.startDiscovery();
停止搜尋:bluetoothAdapter.cancelDiscovery();

每發現一個裝置,系統會發出 ACTION_FOUND 廣播:

BroadcastReceiver deviceFound = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String remoteDeviceName = intent.getStringExtra(BluetoothAdapter.EXTRA_NAME);
        BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothAdapter.EXTRA_DEVICE);
    }
};
registerReceiver(deviceFound, new IntentFilter(BluetoothAdapter.ACTION_FOUND));

6. 建立連線的兩個角色

藍牙連線要分別實作伺服器端 BluetoothServerSocket 與客戶端 BluetoothSocket,概念與 J2SE 的 ServerSocket / Socket 幾乎一致。

伺服器端呼叫 accept() 監聽,當客戶端請求抵達時回傳一個 BluetoothSocket,兩端就能透過 InputStream 與 OutputStream 傳輸資料。

關鍵點:accept() 是阻塞呼叫,絕對不能放在 UI 執行緒,否則畫面會直接卡死。實務上 BluetoothServerSocket 與 BluetoothSocket 都應該各自跑在自己的執行緒裡。

二、開發流程拆解

整體關鍵步驟:

1、開啟藍牙
2、搜尋可用裝置
3、建立藍牙 socket 並取得輸入輸出串流
4、讀寫資料
5、斷線並關閉藍牙

步驟一:加上轉場動畫的 TabHost

由於畫面需要在多頁之間切換,這裡使用 TabHost。原生效果略顯生硬,於是自行覆寫 setCurrentTab 加上平移動畫:

public class AnimationTabHost extends TabHost {
    private int mCurrentTabID = 0;
    private final long mDuration = 400;

    public AnimationTabHost(Context context) { this(context, null); }
    public AnimationTabHost(Context context, AttributeSet attrs) { super(context, attrs); }

    @Override
    public void setCurrentTab(int index) {
        if (index > mCurrentTabID) {
            // 往右切換,舊頁向左平移出去
            TranslateAnimation out = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f,
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f);
            out.setDuration(mDuration);
            getCurrentView().startAnimation(out);
        } else if (index < mCurrentTabID) {
            TranslateAnimation out = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f,
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f);
            out.setDuration(mDuration);
            getCurrentView().startAnimation(out);
        }

        super.setCurrentTab(index);

        if (index > mCurrentTabID) {
            TranslateAnimation in = new TranslateAnimation(
                    Animation.RELATIVE_TO_PARENT, 1.0f, Animation.RELATIVE_TO_PARENT, 0f,
                    Animation.RELATIVE_TO_PARENT, 0f, Animation.RELATIVE_TO_PARENT, 0f);
            in.setDuration(mDuration);
            getCurrentView().startAnimation(in);
        } else if (index < mCurrentTabID) {
            TranslateAnimation in = new TranslateAnimation(
                    Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0f,
                    Animation.RELATIVE_TO_PARENT, 0f, Animation.RELATIVE_TO_PARENT, 0f);
            in.setDuration(mDuration);
            getCurrentView().startAnimation(in);
        }

        mCurrentTabID = index;
    }
}

步驟二:搭建主頁面

主頁面用 TabActivity 承載動畫 TabHost,並用一個靜態的型別列舉標記目前角色:

public class BluetoothActivity extends TabActivity {
    static AnimationTabHost mTabHost;
    static String BlueToothAddress;
    static Type mType = Type.NONE;
    static boolean isOpen = false;

    enum Type { NONE, SERVICE, CILENT }

    private void initTab() {
        mTabHost = (AnimationTabHost) getTabHost();
        mTabHost.addTab(mTabHost.newTabSpec("Tab1")
                .setIndicator("設備列表", getResources().getDrawable(android.R.drawable.ic_menu_add))
                .setContent(new Intent(this, DeviceActivity.class)));
        mTabHost.addTab(mTabHost.newTabSpec("Tab2")
                .setIndicator("會話列表", getResources().getDrawable(android.R.drawable.ic_menu_add))
                .setContent(new Intent(this, ChatActivity.class)));
        mTabHost.setCurrentTab(0);
    }
}

步驟三:裝置列表頁 DeviceActivity

這個頁面的責任是:列出已配對裝置、觸發搜尋、接收 ACTION_FOUND 廣播,並在點選裝置後決定要當伺服器還是客戶端。

public class DeviceActivity extends Activity {
    private ListView mListView;
    private ArrayList<DeviceBean> mDatas;
    private Button mBtnSearch, mBtnService;
    private ChatListAdapter mAdapter;
    private BluetoothAdapter mBtAdapter;

    /** 先列出系統已配對的裝置 */
    private void init() {
        Set<BluetoothDevice> deviceSet = mBtAdapter.getBondedDevices();
        if (deviceSet.size() > 0) {
            for (BluetoothDevice device : deviceSet) {
                mDatas.add(new DeviceBean(device.getName() + "\n" + device.getAddress(), true));
            }
        } else {
            mDatas.add(new DeviceBean("沒有配對的設備", true));
        }
        mAdapter.notifyDataSetChanged();
        mListView.setSelection(mDatas.size() - 1);
    }

    /** 註冊搜尋相關廣播 */
    private void registerBroadcast() {
        registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
    }

    /** 搜尋按鈕 */
    private OnClickListener mSearchListener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if (mBtAdapter.isDiscovering()) {
                mBtAdapter.cancelDiscovery();
                mBtnSearch.setText("重新搜索");
            } else {
                mDatas.clear();
                mAdapter.notifyDataSetChanged();
                init();
                mBtAdapter.startDiscovery();
                mBtnSearch.setText("停止搜索");
            }
        }
    };

    /** 點選裝置後詢問是否連線 */
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            DeviceBean bean = mDatas.get(position);
            String address = bean.message.substring(bean.message.length() - 17);
            BluetoothActivity.BlueToothAddress = address;

            new AlertDialog.Builder(DeviceActivity.this)
                    .setTitle("連接")
                    .setMessage(bean.message)
                    .setPositiveButton("連接", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            mBtAdapter.cancelDiscovery();
                            BluetoothActivity.mType = Type.CILENT;
                            BluetoothActivity.mTabHost.setCurrentTab(1);
                            dialog.cancel();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            BluetoothActivity.BlueToothAddress = null;
                            dialog.cancel();
                        }
                    })
                    .show();
        }
    };

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        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) {
                    mDatas.add(new DeviceBean(device.getName() + "\n" + device.getAddress(), false));
                    mAdapter.notifyDataSetChanged();
                    mListView.setSelection(mDatas.size() - 1);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                if (mListView.getCount() == 0) {
                    mDatas.add(new DeviceBean("沒有發現藍牙設備", false));
                    mAdapter.notifyDataSetChanged();
                }
                mBtnSearch.setText("重新搜索");
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBtAdapter != null) { mBtAdapter.cancelDiscovery(); }
        this.unregisterReceiver(mReceiver);
    }
}

步驟四:會話頁 ChatActivity

這一頁同時負責三件事:跑伺服器或客戶端連線、讀取資料、發送資料。三個執行緒各司其職:

public class ChatActivity extends Activity {
    private static final int STATUS_CONNECT = 0x11;
    private BluetoothServerSocket mServerSocket;  // 伺服器端
    private BluetoothSocket mSocket;              // 客戶端 / 已建立的連線
    private BluetoothDevice mDevice;
    private BluetoothAdapter mBluetoothAdapter;

    private ServerThread mServerThread;
    private ClientThread mClientThread;
    private ReadThread mReadThread;

    public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";

    @Override
    public void onResume() {
        super.onResume();
        if (BluetoothActivity.isOpen) {
            Toast.makeText(this, "連接已經打開,可以通信。若要重建連線請先斷開",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (BluetoothActivity.mType == Type.CILENT) {
            String address = BluetoothActivity.BlueToothAddress;
            if (!"".equals(address)) {
                mDevice = mBluetoothAdapter.getRemoteDevice(address);
                mClientThread = new ClientThread();
                mClientThread.start();
                BluetoothActivity.isOpen = true;
            }
        } else if (BluetoothActivity.mType == Type.SERVICE) {
            mServerThread = new ServerThread();
            mServerThread.start();
            BluetoothActivity.isOpen = true;
        }
    }

    /** 客戶端:主動連向伺服器 */
    private class ClientThread extends Thread {
        public void run() {
            try {
                mSocket = mDevice.createRfcommSocketToServiceRecord(
                        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                Message msg = new Message();
                msg.obj = "請稍候,正在連接服務器:" + BluetoothActivity.BlueToothAddress;
                msg.what = STATUS_CONNECT;
                mHandler.sendMessage(msg);

                mSocket.connect();   // 阻塞,直到連線成功或失敗

                msg = new Message();
                msg.obj = "已經連接上服務端!可以發送信息。";
                msg.what = STATUS_CONNECT;
                mHandler.sendMessage(msg);

                mReadThread = new ReadThread();
                mReadThread.start();
            } catch (IOException e) {
                Message msg = new Message();
                msg.obj = "連接服務端異常!斷開連接重新試一試。";
                msg.what = STATUS_CONNECT;
                mHandler.sendMessage(msg);
            }
        }
    }

    /** 伺服器端:等待對方連入 */
    private class ServerThread extends Thread {
        public void run() {
            try {
                mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
                        PROTOCOL_SCHEME_RFCOMM,
                        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

                mHandler.sendMessage(msgOf("請稍候,正在等待客戶端的連接..."));

                mSocket = mServerSocket.accept();   // 同樣是阻塞呼叫

                mHandler.sendMessage(msgOf("客戶端已經連接上!可以發送信息。"));

                mReadThread = new ReadThread();
                mReadThread.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /** 讀取資料 */
    private class ReadThread extends Thread {
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            InputStream is = null;
            try {
                is = mSocket.getInputStream();
                while (true) {
                    if ((bytes = is.read(buffer)) > 0) {
                        byte[] buf_data = new byte[bytes];
                        for (int i = 0; i < bytes; i++) { buf_data[i] = buffer[i]; }
                        Message msg = new Message();
                        msg.obj = new String(buf_data);
                        msg.what = 1;
                        mHandler.sendMessage(msg);
                    }
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                try { if (is != null) { is.close(); } } catch (IOException e1) { e1.printStackTrace(); }
            }
        }
    }

    /** 發送資料 */
    private void sendMessageHandle(String msg) {
        if (mSocket == null) {
            Toast.makeText(this, "沒有連接", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            OutputStream os = mSocket.getOutputStream();
            os.write(msg.getBytes());
            mDatas.add(new DeviceBean(msg, false));
            mAdapter.notifyDataSetChanged();
            mListView.setSelection(mDatas.size() - 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 關閉伺服器端 */
    private void shutdownServer() {
        new Thread() {
            public void run() {
                if (mServerThread != null) { mServerThread.interrupt(); mServerThread = null; }
                if (mReadThread != null) { mReadThread.interrupt(); mReadThread = null; }
                try {
                    if (mSocket != null) { mSocket.close(); mSocket = null; }
                    if (mServerSocket != null) { mServerSocket.close(); mServerSocket = null; }
                } catch (IOException e) {
                    Log.e("server", "mserverSocket.close()", e);
                }
            }
        }.start();
    }

    /** 關閉客戶端 */
    private void shutdownClient() {
        new Thread() {
            public void run() {
                if (mClientThread != null) { mClientThread.interrupt(); mClientThread = null; }
                if (mReadThread != null) { mReadThread.interrupt(); mReadThread = null; }
                if (mSocket != null) {
                    try { mSocket.close(); } catch (IOException e) { e.printStackTrace(); }
                    mSocket = null;
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (BluetoothActivity.mType == Type.CILENT) {
            shutdownClient();
        } else if (BluetoothActivity.mType == Type.SERVICE) {
            shutdownServer();
        }
        BluetoothActivity.isOpen = false;
        BluetoothActivity.mType = Type.NONE;
    }
}

三、幾個實作上的提醒

UUID 00001101-0000-1000-8000-00805F9B34FB 是 RFCOMM 序列埠的通用 UUID,伺服器與客戶端必須一致,否則永遠連不上。

所有涉及 accept()、connect()、read() 的呼叫都是阻塞的,務必放在子執行緒;而要更新 UI,則透過 Handler 把訊息丟回主執行緒。

Socket 與串流用完記得關閉,並註銷所有 BroadcastReceiver,否則離開頁面後仍會收到廣播而導致記憶體洩漏或崩潰。

完整專案下載:https://pan.baidu.com/s/1eSNRvzG 密碼:awgv

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved