BLE通信(转)

新手刚接触蓝牙4.0,好不容易实现了读取蓝牙上的步数,体重上的数据和血压计的数据。网上资料真的很难找。
扫描蓝牙设备的Activity
public class DeviceScanActivity extends ListActivity {

private final static int REQUEST_ENABLE_BT = 1;
private boolean mScanning;
private LeDeviceListAdapter mLeDeviceListAdapter;
private Handler mHandler;
private BluetoothAdapter mBluetoothAdapter;

private static final long SCAN_PERIOD = 10000;

public static int MY_ACCESS_COARSE_LOCATION = 7895;

boolean mHasPermission = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //getActionBar().setTitle(R.string.title_device);

    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_support, Toast.LENGTH_SHORT).show();
        finish();
    }

    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    if (mBluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_support, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }

    if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
        mHasPermission = false;
    }else {
        mHasPermission = true;
    }

    if(!mHasPermission) {
        //申请ACCESS_COARSE_LOCATION权限
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                MY_ACCESS_COARSE_LOCATION);
        Toast.makeText(this, "do not has ACCESS_COARSE_LOCATION Permission!!!", Toast.LENGTH_LONG).show();
    }
    mHandler = new Handler();

    scanLeDevice(true);
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    doNext(requestCode, grantResults);
}

private void doNext(int requestCode, int[] grantResults) {
    if (requestCode == MY_ACCESS_COARSE_LOCATION) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission Granted 允许授予的权限
            // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
            // BluetoothAdapter through BluetoothManager.
            final BluetoothManager bluetoothManager =
                    (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = bluetoothManager.getAdapter();

            // Checks if Bluetooth is supported on the device.
            if (mBluetoothAdapter == null) {
                //Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
            //mHasPermission = true;
        } else {
            // Permission Denied
            Toast.makeText(this, "No Permission!!!", Toast.LENGTH_LONG).show();
            //mHasPermission = false;
            finish();

        }
    }
}


@Override
protected void onResume() {
    super.onResume();
    if (mHasPermission) {
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(mBluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        mLeDeviceListAdapter = new LeDeviceListAdapter();
        setListAdapter(mLeDeviceListAdapter);
        scanLeDevice(true);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED){
        finish();
        return;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

@Override
protected void onPause() {
    super.onPause();
    mLeDeviceListAdapter.clear();
    scanLeDevice(false);
}

public void scanLeDevice(final boolean enable){
    if(enable){
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                invalidateOptionsMenu();
            }
        },SCAN_PERIOD);
        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    }else {
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
    invalidateOptionsMenu();
}

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mLeDeviceListAdapter.addDevice(device);
                mLeDeviceListAdapter.notifyDataSetChanged();
            }
        });
    }
};

public class LeDeviceListAdapter extends BaseAdapter{
    private ArrayList<BluetoothDevice> mLeDevices;
    private LayoutInflater mInflater;

    public LeDeviceListAdapter(){
        super();
        mLeDevices = new ArrayList<BluetoothDevice>();
        mInflater = DeviceScanActivity.this.getLayoutInflater();
    }

    public void addDevice(BluetoothDevice device){
        if(!mLeDevices.contains(device)){
            mLeDevices.add(device);
        }
    }

    public void clear(){
        mLeDevices.clear();
    }

    public BluetoothDevice getDevice(int position){
        return mLeDevices.get(position);
    }

    @Override
    public int getCount() {
        return mLeDevices.size();
    }

    @Override
    public Object getItem(int position) {
        return mLeDevices.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        ViewHolder viewHolder;
        if(view == null){
            viewHolder = new ViewHolder();
            view = mInflater.inflate(R.layout.listitem_device,null);
            viewHolder.deviceName = (TextView)view.findViewById(R.id.receiver_data_display);
            viewHolder.deviceAddress = (TextView)view.findViewById(R.id.device_address_display);
            view.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder)view.getTag();
        }
        BluetoothDevice device = mLeDevices.get(position);
        final String deviceName = device.getName();
        if(deviceName != null && deviceName.length()>0)
            viewHolder.deviceName.setText(deviceName);
        else
            viewHolder.deviceName.setText(R.string.unknow_device);
        viewHolder.deviceAddress.setText(device.getAddress());
        return view;
    }
}

public class ViewHolder {
    TextView deviceName;
    TextView deviceAddress;
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if(device == null) return;
    Intent intent = new Intent(this,DeviceControlActivity.class);
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME,device.getName());
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS,device.getAddress());
    if(mScanning){
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
    startActivity(intent);
}

}

管理设备和显示数据的Activity
public class DeviceControlActivity extends Activity {

public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private String mDeviceName;
private String mDeviceAddress;

private TextView mConnectionState;
private TextView mBattery;
private TextView mBleBattery;
private TextView mManufacturer;
private TextView mStepCount;
private TextView mBodyWeight;
private TextView mShrink;
private TextView mDiastole;
private TextView mHeartRate;
private TextView mRange;
//private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
private MyThread mt = null;
private double weight;
private boolean finish = true;

private boolean mConnected = false;


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

    Intent intent = getIntent();
    mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
    mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);

    mBattery = (TextView)findViewById(R.id.battery);
    mBleBattery = (TextView)findViewById(R.id.ble_battery);
    mManufacturer = (TextView)findViewById(R.id.manufacturer);
    mStepCount = (TextView)findViewById(R.id.step_count);
    mBodyWeight = (TextView)findViewById(R.id.body_weight);
    mShrink = (TextView)findViewById(R.id.shrink);
    mDiastole = (TextView)findViewById(R.id.diastole);
    mHeartRate = (TextView)findViewById(R.id.heart_rate);
    mRange = (TextView)findViewById(R.id.range);

    ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
    mConnectionState = (TextView) findViewById(R.id.connection_state);
    getActionBar().setTitle(mDeviceName);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
    bindService(gattServiceIntent, conn, BIND_AUTO_CREATE);

}

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                String battery = msg.getData().getString("battery");
                if (battery != null) {
                    Log.d("demo", String.valueOf(Integer.parseInt(battery, 16)));
                    int level = Integer.parseInt(battery, 16);
                    mBleBattery.setText(level + "%");
                }
                break;
            case 2:
                String manufacturer = msg.getData().getString("manufacturer");
                if (manufacturer != null) {
                    mManufacturer.setText(manufacturer);
                }
                break;
            case 3:
                String data = msg.getData().getString("count");
                String count = data.substring(4, 10);
                int stepCount = Integer.parseInt(count, 16);
                mStepCount.setText(stepCount + "");
                break;
            case 4:
                String body_weight = msg.getData().getString("bodyweight");
                String bw = body_weight.substring(4, 8);
                getWeight(bw);
                break;
            case 5:
                Bundle b = msg.getData();
                mBodyWeight.setText(b.getDouble("weight")+" kg");
                if (weight == 0.0) {
                    mHandler.removeCallbacks(mt);
                    mt = null;
                }
                break;
            case 6:
                String blood = msg.getData().getString("bloodpressure");
                getBloodPressure(blood);
                break;
            default:
                break;
        }
    }
};

public void getBloodPressure(String data){
    String sk = data.substring(20,24);
    int shrink = Integer.parseInt(sk,16);
    mShrink.setText(shrink+" mmHg");
    String dia = data.substring(24,26);
    int diastole = Integer.parseInt(dia,16);
    mDiastole.setText(diastole+" mmHg");
    String hr = data.substring(26,28);
    int heart = Integer.parseInt(hr,16);
    mHeartRate.setText(heart+" BPM");
    getRange(shrink,diastole);
}

public void getRange(int shrink,int diastole){
    if((shrink>=90 && shrink<140) && (diastole>=60 && diastole<90)){
        mRange.setText(R.string.normal);
    }else if(shrink>139 || diastole>90){
        mRange.setText(R.string.high);
    }else if(shrink<90 || diastole<60){
        mRange.setText(R.string.low);
    }else if(shrink>139 && diastole<90){
        mRange.setText(R.string.isolated_systolic_hypertension);
    }
}


public void getWeight(String s){
    int a = Integer.parseInt(s,16);
    if (mt == null) {
        mt = new MyThread();
        mt.start();
    }
    double w = a;
    weight = w/10;
}
@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
}

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

@Override
protected void onDestroy() {
    super.onDestroy();
    unbindService(conn);
    mBluetoothLeService = null;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.gatt_service, menu);
    if (mConnected) {
        menu.findItem(R.id.menu_connect).setVisible(false);
        menu.findItem(R.id.menu_disconnect).setVisible(true);
    } else {
        menu.findItem(R.id.menu_connect).setVisible(true);
        menu.findItem(R.id.menu_disconnect).setVisible(false);
    }
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_connect:
            mBluetoothLeService.connect(mDeviceAddress);
            return true;
        case R.id.menu_disconnect:
            mBluetoothLeService.disconnect();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

private final ServiceConnection conn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mBluetoothLeService = ((BluetoothLeService.LocalBind) service).getService();
        if (!mBluetoothLeService.initialize()) {
            finish();
        }
        mBluetoothLeService.connect(mDeviceAddress);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mBluetoothLeService = null;
    }
};


private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        Bundle bundle = new Bundle();
        Message msg = new Message();
        Log.d("demo", action);
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            mConnected = true;
            updateConnectionState(R.string.connected);
            invalidateOptionsMenu();
        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
            mConnected = false;
            updateConnectionState(R.string.disconnected);
            invalidateOptionsMenu();
            //clearUI();
        } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVER.equals(action)) {
            mBluetoothLeService.readBattery();
        } else if (BluetoothLeService.ACTION_DATA_BLOODPRESSURE.equals(action)) {
            //displayBloodPressure(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            bundle.putString("bloodpressure", intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            msg.setData(bundle);
            msg.what = 6;
            mHandler.sendMessage(msg);
        } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
            int level = intent.getIntExtra("level", 0);//获取当前电量
            int scale = intent.getIntExtra("scale", 100);//电量的总刻度
            mBattery.setText(((level * 100) / scale) + "%");//把它转成百分比
        } else if (BluetoothLeService.ACTION_DATA_BATTERY.equals(action)) {
            //displayBleBattery(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            bundle.putString("battery", intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            msg.setData(bundle);
            msg.what = 1;
            mHandler.sendMessage(msg);
        } else if (BluetoothLeService.ACTION_DATA_MENUFACTURER.equals(action)) {
            //displayManufacturer(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            bundle.putString("manufacturer", intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            msg.setData(bundle);
            msg.what = 2;
            mHandler.sendMessage(msg);
        } else if (BluetoothLeService.ACTION_DATA_COUNT.equals(action)) {
            //displayCount(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            bundle.putString("count", intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            msg.setData(bundle);
            msg.what = 3;
            mHandler.sendMessage(msg);
        } else if (BluetoothLeService.ACTION_DATA_BODYWEIGHT.equals(action)) {
            //displayBodyWeight(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            bundle.putString("bodyweight", intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            msg.setData(bundle);
            msg.what = 4;
            mHandler.sendMessage(msg);
        }
    }
};

private void updateConnectionState(final int resourceId) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mConnectionState.setText(resourceId);
        }
    });
}

/*private void clearUI() {
    mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
}*/

/* private void displayBloodPressure(String data) {
if (data != null) {
mBloodPressure.setText(data);
}
}

private void displayBodyWeight(String data) {
    if (data != null) {
        mBodyWeight.setText(data);
    }
}*/

/* public void displayBleBattery(String data){
Log.d(“demo”, “battery data != null —>”+String.valueOf(data!=null));
if(data != null){
Log.d(“demo”, String.valueOf(Integer.parseInt(data,16)));
int level = Integer.parseInt(data, 16);
mBleBattery.setText(level+”%”);
}
}*/

/* public void displayManufacturer(String data) {
if (data != null) {
mManufacturer.setText(data);
}
}

public void displayCount(String data) {
    if (data != null) {
        String count = data.substring(4, 10);
        Log.d("demo", count);
        Log.d("demo", String.valueOf(Integer.parseInt(count, 16)));
        int stepCount = Integer.parseInt(count, 16);
        mStepCount.setText(stepCount + "");
    }
}*/

private static IntentFilter makeGattUpdateIntentFilter() {
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
    intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
    intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVER);
    intentFilter.addAction(BluetoothLeService.ACTION_DATA_BLOODPRESSURE);
    intentFilter.addAction(BluetoothLeService.ACTION_DATA_BODYWEIGHT);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(BluetoothLeService.ACTION_DATA_MENUFACTURER);
    intentFilter.addAction(BluetoothLeService.ACTION_DATA_BATTERY);
    intentFilter.addAction(BluetoothLeService.ACTION_DATA_COUNT);
    return intentFilter;
}

class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        while (finish) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Message msg = new Message();
            Bundle bundle = new Bundle();
            bundle.putDouble("weight", weight);
            msg.setData(bundle);
            msg.what = 5;
            mHandler.sendMessage(msg);
        }
    }

}

}
服务类
public class BluetoothLeService extends Service {
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;
private Handler mHandler = new Handler();

private final static int STATE_DISCONNECTED = 0;
private final static int STATE_CONNECTING = 1;
private final static int STATE_CONNECTED = 2;

private final static int RUN_PERIOD = 3000;
private final static int COUNT_PERIOD = 3000;

public final static String ACTION_GATT_CONNECTED = "com.example.chongyanghu.ble.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED = "com.example.chongyanghu.ble.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVER = "com.example.chongyanghu.ble.ACTION_GATT_SERVICES_DISCOVER";

public final static String EXTRA_DATA = "com.example.chongyanghu.ble.EXTRA_DATA";
public final static String ACTION_DATA_BATTERY = "com.example.chongyanghu.ble.ACTION_DATA_BATTERY";
public final static String ACTION_DATA_MENUFACTURER = "com.example.chongyanghu.ble.ACTION_DATA_MENUFACTURER";
public final static String ACTION_DATA_COUNT = "com.example.chongyanghu.ble.ACTION_DATA_COUNT";
public final static String ACTION_DATA_BLOODPRESSURE = "com.example.chongyanghu.ble.ACTION_DATA_BLOODPRESSURE";
public final static String ACTION_DATA_BODYWEIGHT = "com.example.chongyanghu.ble.ACTION_DATA_BODYWEIGHT";

//public final static UUID UUID_HEART_RATE_MEASUREMENT = UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);

public final static String BATTERY_SERVICE = "0000180F-0000-1000-8000-00805f9b34fb";
public final static String BATTERY_CHARATERISTIC = "00002a19-0000-1000-8000-00805f9b34fb";
public final static String MANUFACTURER_SERVICE = "0000180a-0000-1000-8000-00805f9b34fb";
public final static String MANUFACTURER_CHARATERISTIC = "00002a29-0000-1000-8000-00805f9b34fb";
public final static String CUSTOM_SERVICE = "0000ffe0-0000-1000-8000-00805f9b34fb";
public final static String CUSTOM_CHARACTERISTIC = "0000ffe1-0000-1000-8000-00805f9b34fb";


private final IBinder mBinder = new LocalBind();

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

public class LocalBind extends Binder {
    BluetoothLeService getService() {
        return BluetoothLeService.this;
    }
}

@Override
public boolean onUnbind(Intent intent) {
    close();
    return super.onUnbind(intent);
}

public boolean initialize() {
    if (mBluetoothManager == null) {
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager == null) {
            return false;
        }
    }
    mBluetoothAdapter = mBluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        return false;
    }
    return true;
}

public void disconnect() {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.disconnect();
}

public boolean connect(final String address) {
    if (mBluetoothAdapter == null || address == null) {
        return false;
    }
    if (mBluetoothDeviceAddress != null && mBluetoothGatt != null
            && address.equals(mBluetoothDeviceAddress)) {
        if (mBluetoothGatt.connect()) {
            mConnectionState = STATE_CONNECTING;
            return true;
        } else {
            return false;
        }
    }
    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        return false;
    }
    mBluetoothGatt = device.connectGatt(this, false, mGattCallBack);
    mBluetoothDeviceAddress = address;
    mConnectionState = STATE_CONNECTING;
    return true;
}

private final BluetoothGattCallback mGattCallBack = new BluetoothGattCallback() {

    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;
            broadcastUpdate(intentAction);
            mBluetoothGatt.discoverServices();
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            broadcastUpdate(intentAction);
        }
    }


    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        Log.d("demo", "onCharacteristicChanged");
        byte[] data = characteristic.getValue();
        final StringBuilder stringBuilder = new StringBuilder(data.length);
        for (byte byteChar : data)
            stringBuilder.append(String.format("%02X", byteChar));
        String builder = stringBuilder.toString();
        Log.d("demo", "0x -->" + builder);
        if(data[0] == (byte)0xC1){
            broadcastUpdate(ACTION_DATA_COUNT, characteristic);
        }else if(data[0] == (byte)0xB1){
            broadcastUpdate(ACTION_DATA_BLOODPRESSURE, characteristic);
        }else if(data[0] == (byte)0xB7){
            broadcastUpdate(ACTION_DATA_BODYWEIGHT, characteristic);
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVER);
        }
    }

    @Override
    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        UUID uuid = descriptor.getCharacteristic().getUuid();

    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.d("demo", "state = " + String.valueOf(status == BluetoothGatt.GATT_SUCCESS));
            if (characteristic.getUuid().toString().equalsIgnoreCase(BATTERY_CHARATERISTIC)) {
                Log.d("demo", String.valueOf(characteristic.getValue()[0]));
                broadcastUpdate(ACTION_DATA_BATTERY, characteristic);
            } else if (characteristic.getUuid().toString().equalsIgnoreCase(MANUFACTURER_CHARATERISTIC)) {
                Log.d("demo", "readManufacturer");
                broadcastUpdate(ACTION_DATA_MENUFACTURER, characteristic);
            }
        }
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);
    }
};

//打开设备的通知功能
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable) {
    Log.d("demo", "setCharacteristicNotification");
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.setCharacteristicNotification(characteristic, enable);

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);
}

public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothGatt == null || mBluetoothAdapter == null) {
        return;
    }
    Log.d("demo", "readCharacteristic");
    mBluetoothGatt.readCharacteristic(characteristic);
}

private void broadcastUpdate(String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

private void broadcastUpdate(String action, BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);
    String uuid = characteristic.getUuid().toString();
    Log.d("demo", "into broadcastUpdate");
    if (uuid.equalsIgnoreCase(BATTERY_CHARATERISTIC)) {
        byte[] databattery = characteristic.getValue();
        analysisData(intent, databattery);
    } else if (uuid.equalsIgnoreCase(MANUFACTURER_CHARATERISTIC)) {
        final byte[] datamanufacturer = characteristic.getValue();
        intent.putExtra(EXTRA_DATA,new String(datamanufacturer));
        sendBroadcast(intent);
    } else if (uuid.equalsIgnoreCase(CUSTOM_CHARACTERISTIC)) {
        byte[] data = characteristic.getValue();
        analysisData(intent,data);
    }
}


public void analysisData(Intent intent, byte[] data) {
    if (data != null && data.length > 0) {
        final StringBuilder stringBuilder = new StringBuilder(data.length);
        Log.d("demo", String.valueOf(data.length));
        for (byte byteChar : data)
            stringBuilder.append(String.format("%02X", byteChar));
        String builder = stringBuilder.toString();
        Log.d("demo", "0x -->" + builder);
        intent.putExtra(EXTRA_DATA,builder);
        sendBroadcast(intent);
    }
}

public void close() {
    if (mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.close();
    mBluetoothGatt = null;
}

public List<BluetoothGattService> getSupportedGattServices() {
    if (mBluetoothGatt == null) return null;
    return mBluetoothGatt.getServices();
}

public void readBattery() {
    Log.d("demo", "readBattery");
    BluetoothGattService batteryService = mBluetoothGatt.getService(UUID.fromString(BATTERY_SERVICE));
    if (batteryService != null) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Handler mHandler = new Handler();
                BluetoothGattService manufacturerService = mBluetoothGatt.getService(UUID.fromString(MANUFACTURER_SERVICE));
                if (manufacturerService != null) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            BluetoothGattService customService = mBluetoothGatt.getService(UUID.fromString(CUSTOM_SERVICE));
                            if (customService != null) {
                                BluetoothGattCharacteristic customCharacteristic = customService.getCharacteristic(UUID.fromString(CUSTOM_CHARACTERISTIC));
                                if (customCharacteristic != null) {
                                    final int charaProp = customCharacteristic.getProperties();
                                    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                                        setCharacteristicNotification(customCharacteristic, true);
                                    }
                                }
                            }
                        }
                    }, COUNT_PERIOD);
                    BluetoothGattCharacteristic manufacturerCharacteristic = manufacturerService.getCharacteristic(UUID.fromString(MANUFACTURER_CHARATERISTIC));
                    Log.d("demo", "manufacturerCharacteristic = " + String.valueOf(manufacturerCharacteristic != null));
                    final int charaProp = manufacturerCharacteristic.getProperties();
                    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                        Log.d("demo", "intoNotify--->" + String.valueOf((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0));
                        readCharacteristic(manufacturerCharacteristic);
                    }
                }
            }
        }, RUN_PERIOD);
        BluetoothGattCharacteristic batteryCharacteristic = batteryService.getCharacteristic(UUID.fromString(BATTERY_CHARATERISTIC));
        if (batteryCharacteristic != null) {
            readCharacteristic(batteryCharacteristic);
        }
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值