Android和蓝牙设备之间的通信

时间:2017-05-08 02:12:33

标签: java android bluetooth

我想将Android应用程序和传感器与蓝牙连接并在应用程序上显示传感器数据,但我不知道在哪里更改。

传感器的数据是否存储在角色棒中? 如果是这样,您如何显示存储的数据?

您使用的设备是SONY MESH按钮。 Android版本5.0.2 Android Studio ver 2.3.1

MainActivity.java

private final static int SDKVER_LOLLIPOP = 21;
private final static int MESSAGE_NEW_RECEIVEDNUM = 0;
private final static int MESSAGE_NEW_SENDNUM = 1;
private final static int REQUEST_ENABLE_BT = 123456;
private BluetoothManager mBleManager;
private BluetoothAdapter mBleAdapter;
private boolean mIsBluetoothEnable = false;
private BluetoothLeScanner mBleScanner;
private BluetoothGatt mBleGatt;
private BluetoothGattCharacteristic mBleCharacteristic;
private TextView mTxtReceivedNum;
private TextView mTxtSendNum;
private String meshdata = String.valueOf(0x00020103);
private String mStrReceivedNum = "";
private String mStrSendNum = "";


private static final String SERVICE_UUID = "72C90001-57A9-4D40-B746-534E22EC9F9E";

private static final String CHARACTERISTIC_UUID = "72C90003-57A9-4D40-B746-534E22EC9F9E";

private static final String CHARACTERISTIC_CONFIG_UUID = "00002902-0000-1000-8000-00805f9b34fb";


private Random mRandom = new Random();
private Timer mTimer;
private SendDataTimer mSendDataTimer;

private final LeScanCallback mScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                mBleGatt = device.connectGatt(getApplicationContext(), false, mGattCallback);
            }
        });
    }
};
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
    {

        if (newState == BluetoothProfile.STATE_CONNECTED) {

            gatt.discoverServices();
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

            if (mBleGatt != null)
            {
                mBleGatt.close();
                mBleGatt = null;
            }
            mIsBluetoothEnable = false;
        }
    }
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status)
    {

        if (status == BluetoothGatt.GATT_SUCCESS) {

            BluetoothGattService service = gatt.getService(UUID.fromString(SERVICE_UUID));
            if (service != null)
            {

                mBleCharacteristic = service.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID));

                if (mBleCharacteristic != null) {

                    mBleGatt = gatt;


                    boolean registered = mBleGatt.setCharacteristicNotification(mBleCharacteristic, true);


                    BluetoothGattDescriptor descriptor = mBleCharacteristic.getDescriptor(
                            UUID.fromString(CHARACTERISTIC_CONFIG_UUID));

                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mBleGatt.writeDescriptor(descriptor);

                    mIsBluetoothEnable = true;
                }
            }
        }
    }
    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
    {

        if (CHARACTERISTIC_UUID.equals(characteristic.getUuid().toString().toUpperCase()))
        {

            mStrReceivedNum = characteristic.getStringValue(0);

            mBleHandler.sendEmptyMessage(MESSAGE_NEW_RECEIVEDNUM);
        }
    }
};
private Handler mBleHandler = new Handler()
{
    public void handleMessage(Message msg)
    {

        switch (msg.what)
        {
            case MESSAGE_NEW_RECEIVEDNUM:
                mTxtReceivedNum.setText(mStrReceivedNum);
                break;
            case MESSAGE_NEW_SENDNUM:
                mTxtSendNum.setText(mStrSendNum);
                break;
        }
    }
};

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

    mIsBluetoothEnable = false;


    mTxtReceivedNum = (TextView) findViewById(R.id.received_num);
    mTxtSendNum = (TextView) findViewById(R.id.send_num);


    mBleManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBleAdapter = mBleManager.getAdapter();


    mTimer = new Timer();
    mSendDataTimer = new SendDataTimer();

    mTimer.schedule(mSendDataTimer, 500, 1000);


    if ((mBleAdapter == null)
            || (! mBleAdapter.isEnabled())) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
    else
    {

        this.scanNewDevice();
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQUEST_ENABLE_BT:
            if ((mBleAdapter != null)
                    || (mBleAdapter.isEnabled())) {

                this.scanNewDevice();
            }
            break;
    }
}
private void scanNewDevice()
{

    if (Build.VERSION.SDK_INT >= SDKVER_LOLLIPOP)
    {
        this.startScanByBleScanner();
    }
    else
    {

        mBleAdapter.startLeScan(mScanCallback);
    }
}
@TargetApi(SDKVER_LOLLIPOP)
private void startScanByBleScanner()
{
    mBleScanner = mBleAdapter.getBluetoothLeScanner();

    mBleScanner.startScan(new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            result.getDevice().connectGatt(getApplicationContext(), false, mGattCallback);
        }
        @Override
        public void onScanFailed(int intErrorCode)
        {
            super.onScanFailed(intErrorCode);
        }
    });
}
public class SendDataTimer extends TimerTask{
    @Override
    public void run() {
        if(mIsBluetoothEnable)
        {

            mStrSendNum = String.valueOf(mRandom.nextInt(1000));

            mBleHandler.sendEmptyMessage(MESSAGE_NEW_SENDNUM);

            mBleCharacteristic.setValue(meshdata);
            mBleGatt.writeCharacteristic(mBleCharacteristic);
        }
    }
}
@Override
protected void onDestroy()
{

    mIsBluetoothEnable = false;
    if(mBleGatt != null) {
        mBleGatt.close();
        mBleGatt = null;
    }
    super.onDestroy();
}

相关地点

@Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
    {

        if (CHARACTERISTIC_UUID.equals(characteristic.getUuid().toString().toUpperCase()))
        {

            mStrReceivedNum = characteristic.getStringValue(0);

            mBleHandler.sendEmptyMessage(MESSAGE_NEW_RECEIVEDNUM);
        }
    }

相关地点

    private Handler mBleHandler = new Handler()
{
    public void handleMessage(Message msg)
    {

        switch (msg.what)
        {
            case MESSAGE_NEW_RECEIVEDNUM:
                mTxtReceivedNum.setText(mStrReceivedNum);
                break;
            case MESSAGE_NEW_SENDNUM:
                mTxtSendNum.setText(mStrSendNum);
                break;
        }
    }
};

相关地点

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

    mIsBluetoothEnable = false;


    mTxtReceivedNum = (TextView) findViewById(R.id.received_num);
    mTxtSendNum = (TextView) findViewById(R.id.send_num);

相关地点

public class SendDataTimer extends TimerTask{
    @Override
    public void run() {
        if(mIsBluetoothEnable)
        {

            mStrSendNum = String.valueOf(mRandom.nextInt(1000));

            mBleHandler.sendEmptyMessage(MESSAGE_NEW_SENDNUM);

            mBleCharacteristic.setValue(mStrSendNum);
            mBleGatt.writeCharacteristic(mBleCharacteristic);
        }
    }
}

activity_main.xml中

<TextView
    android:id="@+id/received_num"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="40sp"
    android:gravity="right"
     />

<TextView
    android:id="@+id/send_num"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="40sp"
    />

0 个答案:

没有答案