1. 程式人生 > >【TL8266】APP接收藍芽模組傳送過來的訊息

【TL8266】APP接收藍芽模組傳送過來的訊息

前一篇文章講述瞭如何向藍芽模組傳送資料,這一篇講述如何接收資料,點選開關按鈕傳送AT指令,模組會返回OK
這裡寫圖片描述

先做一個廣播接收器,按Ctrl+F關注mBluetoothLeService的操作

public class BleAtActivity extends Activity implements View.OnClickListener{

    private BroadcastReceiver mGattUpdateBroadcastReceiver=new BroadcastReceiver() {
        @Override
        public void
onReceive(Context context, Intent intent) { String action=intent.getAction(); if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)){ mBluetoothLeService.connect(mAddressString); } if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)){ displayData(intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA)); } } }; }

其中接收到的資料是byte[]型別,轉換成string型別,以吐司的方式顯示出來,核心是對bytes的操作

public class BleAtActivity extends Activity implements View.OnClickListener{

    private void displayData(byte[] buf) {
        String s =asciiToString(buf);
        Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
    }

    public String asciiToString
(byte[] bytes) { char[] buf = new char[bytes.length]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.length; i++) { buf[i] = (char) bytes[i]; sb.append(buf[i]); } return sb.toString(); } }

再做一個過濾器,用於選擇與藍芽有關的廣播

public class BleAtActivity extends Activity implements View.OnClickListener{

    private IntentFilter makeGattUpdateIntentFilter(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_WRITE_SUCCESSFUL);
        return intentFilter;
    }

}

註冊。上面做了那麼多都是為了registerReceiver函式,前面都是初始化,只有這一步是有效操作

public class BleAtActivity extends Activity implements View.OnClickListener{

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateBroadcastReceiver, makeGattUpdateIntentFilter());
        if (mBluetoothLeService!=null){
            mBluetoothLeService.connect(mAddressString);

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateBroadcastReceiver);
    }

}

其他部分基本和前一篇沒什麼區別,其實應該寫成一篇,不過考慮到前面一篇那麼長,還是分開吧

原始碼地址