Android(藍芽)

來源:互聯網
上載者:User

標籤:

因近期項目需求調試了Android藍芽通訊介面,主要是兩個終端作為服務端和用戶端的通訊,本文將部分重要知識點記錄如下。

藍芽是短距離無線通訊,通常分經典藍芽和低功耗藍芽(即藍芽4.0),兩類藍芽協議各層定義上存在很多不同,因此晶片也不一樣,但就Android上做應用程式層開發沒什麼差別。

藍芽通訊分為配對和資料轉送兩部分,兩部分是獨立的,一般來說是點對點,如果要組區域網路需要支援LAN協議擴充,沒有嘗試過。

  • 配對階段
    • 發現裝置方
           
       mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.enable(); IntentFilter intent = new IntentFilter(); intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver來取得搜尋結果 receiver = new BluetoothReceiver(); registerReceiver(receiver, intent);//註冊一個廣播,接收藍牙裝置發現的訊息 mBluetoothAdapter.startDiscovery();
    private class BluetoothReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            if(BluetoothDevice.ACTION_FOUND.equals(action))            {                if(isFound == true){                    return;                }                isFound = true;                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//擷取這個藍牙裝置,可能存在多個
    • 被發現方
        Intent discoveryIntent = new Intent(                BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);        discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,                300);//彈出一個視窗,確認本機藍牙裝置在300s內可被發現        discoveryIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        startActivity(discoveryIntent);
  • 通訊階段

通訊階段基本等價於socket編程,本文不黏貼全部代碼,唯一遇到的問題是不用反射方法擷取裝置,通訊串連很不穩定,本文代碼如下:

    • 伺服器端
Method listenMethod = adapter.getClass().getMethod("listenUsingRfcommOn", new Class[]{int.class});mmServerSocket = ( BluetoothServerSocket) listenMethod.invoke(adapter, Integer.valueOf(1));socket = mmServerSocket.accept();
    • 用戶端
Method method = mServerDevice.getClass().getMethod("createRfcommSocket",new Class[] { int.class });mSocket = (BluetoothSocket) method.invoke(mServerDevice, Integer.valueOf(1));

Android(藍芽)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.