Android手机与BLE终端通信

      Android 开发BLE通信,代码只能接收数据,没有写发送数据部分,接收数据时间间隔可自己修改,是工程中的一部分,只涉及蓝牙部分。代码中的UUID部分需要按自己的设备修改。

    代码下载地址:http://download.csdn.net/download/auroraexecue/9931371


布局部分:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.hp.blecaresystem.MainActivity">

    <TextView
        android:layout_centerInParent="true"
        android:id="@+id/stata_data_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="数据显示"
        android:textSize="20dp"/>

    <LinearLayout
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/start_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="连接蓝牙"/>

        <TextView
            android:layout_width="40dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/stop_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="断开设备"/>
    </LinearLayout>
</RelativeLayout>

Activity部分:

public class MainActivity extends AppCompatActivity {
    private Button start_button;
    private TextView stata_data_show;
    private Button stop_button;
    public final static String ACTION_DEVICE_CONECT = "com.example.hp.blecaresystem.ACTION_DEVICE_CONECT";
    public final static String ACTION_DEVICE_DISCONECT = "com.example.hp.blecaresystem.ACTION_DEVICE_DISCONECT";
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private static final int ENABLE_BT_REQUEST_ID = 1;
    private final static int msg_deviceconnected = 1;
    private final static int msg_devicedisconnected = 2;
    private final static int msg_bluedatachaged = 3;
    private static short[] raw_data;

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

        serviceinit();
        viewInit();
        blueInit();
        regesterReciver();
    }

    private void viewInit(){
        stata_data_show = (TextView) findViewById(R.id.stata_data_show);
        start_button = (Button)findViewById(R.id.start_button);
        stop_button = (Button)findViewById(R.id.stop_button);
        start_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent= new Intent(ACTION_DEVICE_CONECT);
                sendBroadcast(intent);

            }
        });
        stop_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent= new Intent(ACTION_DEVICE_DISCONECT);
                sendBroadcast(intent);
            }
        });
    }

    private void serviceinit(){
        Intent intent = new Intent(MainActivity.this,BLEService.class);
        startService(intent);
    }

    private void blueInit(){
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, ENABLE_BT_REQUEST_ID);
        }
    }

    private void regesterReciver(){
        IntentFilter mfilter = new IntentFilter();
        mfilter.addAction(BLEService.ACTION_GATT_CONNECTED);
        mfilter.addAction(BLEService.ACTION_GATT_DISCONNECTED);
        mfilter.addAction(BLEService.ACTION_DATA_AVAILABLE);
        registerReceiver(mReciver,mfilter);
    }
    private void unregesterReciver(){
        unregisterReceiver(mReciver);
    }
    private BroadcastReceiver mReciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BLEService.ACTION_GATT_CONNECTED)){
                mHandler.sendEmptyMessage(msg_deviceconnected);
            }else if (action.equals(BLEService.ACTION_GATT_DISCONNECTED)){
                mHandler.sendEmptyMessage(msg_devicedisconnected);
            }else if (action.equals(BLEService.ACTION_DATA_AVAILABLE)){
                raw_data = intent.getShortArrayExtra("rawdata");
                mHandler.sendEmptyMessage(msg_bluedatachaged);
            }
        }
    };
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case msg_deviceconnected:
                    Toast.makeText(MainActivity.this,"蓝牙已连接!",Toast.LENGTH_SHORT).show();
                    break;
                case msg_devicedisconnected:
                    Toast.makeText(MainActivity.this,"蓝牙已断开!",Toast.LENGTH_SHORT).show();
                    break;
                case msg_bluedatachaged:
                    if (raw_data!=null && raw_data.length>0)
                        stata_data_show.setText("" + raw_data[0] + " " + raw_data[1] + " " + raw_data[2]);
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregesterReciver();
    }
}

UUID 类部分:

public class BleDefinedUUIDS {
      final static public UUID CHARACTER_UUID = UUID.fromString("00001527-1212-efde-1523-785feabcd123");
      final static public UUID SERVICE_UUID = UUID.fromString("00001526-1212-efde-1523-785feabcd123");
}

Service部分:

public class BLEService extends Service {
    private final static String TAG = BLEService.class.getCanonicalName();
    public final static String ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String ACTION_EXTRA_DATA = "com.example.bluetooth.le.ACTION_EXTRA_DATA";
    private final static int msg_startconnect = 1;
    private final static int msg_connectdevice = 2;
    private final static int msg_disconnecte = 3;
    private final static int msg_getbluedata = 4;
    private final static int msg_datagetted = 5;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private BluetoothGattCharacteristic mCharacteristic;
    private static short[] GESONSOR_DATA;
    private BluetoothGatt mBluetoothGatt = null;
    private final static String BLUE_ADRESS = "F7:96:42:E4:8C:57";
    private BluetoothDevice DEVICE = null;
    private static boolean bluedatastate = false;
    private final static int GET_DATA_TIME = 100; //间隔100毫秒获得一次数据

    public BLEService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        regesterReciver();

        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
    }
    public void startScanning() {
        final UUID[] uuids = new UUID[] { BleDefinedUUIDS.SERVICE_UUID };
        mBluetoothAdapter.startLeScan(uuids,mDeviceFoundCallback);
    }

    /* stops current scanning */
    public void stopScanning() {
        mBluetoothAdapter.stopLeScan(mDeviceFoundCallback);
    }

    private BluetoothAdapter.LeScanCallback mDeviceFoundCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int i, byte[] bytes) {
            if (IsTargetBlueDecive(device)){
                stopScanning();
            }
        }
    };

    private boolean IsTargetBlueDecive(BluetoothDevice device){
        if (device == null)
            return false;
        if (device.getAddress().equals(BLUE_ADRESS)){
            this.DEVICE = device;
            mHandler.sendEmptyMessage(msg_connectdevice);
            return true;
        }
        return false;
    }

    private boolean connectDevice(String address){
        if (mBluetoothAdapter==null || address==null)
            return false;
        //如果之前有连接过就直接连接,重新连接
        if (mBluetoothGatt != null)
            return mBluetoothGatt.connect();
        mBluetoothGatt = DEVICE.connectGatt(this,false,mGattCallback);
        return true;
    }

    public void disconnectDevice()
    {
        if (mBluetoothGatt != null)
        {
            mBluetoothGatt.disconnect();
        }
    }

    public void closeDevice()
    {
        if (mBluetoothGatt != null)
        {
            mBluetoothGatt.close();
        }
    }
    public void requestCharacteristicValue(BluetoothGattCharacteristic ch) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null)
            return;
        mBluetoothGatt.readCharacteristic(ch);
    }

    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        /**
         * 连接状态改变回调
         * @param gatt
         * @param status
         * @param newState
         */
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED){
                mBluetoothGatt.discoverServices();
                Log.w(TAG, "onConnectionStateChange" + " = " + mBluetoothGatt);
                Intent intent = new Intent(ACTION_GATT_CONNECTED);
                sendBroadcast(intent);
                Log.w(TAG, "handleMessage" + " = 连接成功!");
            }else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Intent intent = new Intent(ACTION_GATT_DISCONNECTED);
                sendBroadcast(intent);
                bluedatastate = false;
                Log.w(TAG, "handleMessage" + " = 连接断开!");
            }
        }
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // now, when services discovery is finished, we can call getServices() for Gatt
                mCharacteristic = mBluetoothGatt.getService(BleDefinedUUIDS.SERVICE_UUID)
                        .getCharacteristic(BleDefinedUUIDS.CHARACTER_UUID);
                mHandler.sendEmptyMessage(msg_getbluedata);
                Log.w(TAG, "onServicesDiscovered" + " = " + mCharacteristic);
            }else {

                Log.w(TAG, "onServicesDiscovered" + "获取失败");
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            Log.w(TAG, "onCharacteristicRead" + " = 获得数据一次!");
            getCharacteristicValue(characteristic);
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS){
                Log.w(TAG, "onCharacteristicRead" + " = 获得数据一次!");
                getCharacteristicValue(characteristic);
            }
        }
    };

    public void getCharacteristicValue(BluetoothGattCharacteristic ch) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null || ch == null)
            return;
        byte[] rawValue = ch.getValue();
        UUID uuid = ch.getUuid();
        if (uuid.equals(BleDefinedUUIDS.CHARACTER_UUID)){
            GESONSOR_DATA = toShortArray(rawValue);
            mHandler.sendEmptyMessage(msg_datagetted);
            Log.w(TAG, "getCharacteristicValue=" + GESONSOR_DATA[0] + " " + GESONSOR_DATA[1] + " " + GESONSOR_DATA[2]
                    + " " + GESONSOR_DATA[3] + " " + GESONSOR_DATA[4] + " " + GESONSOR_DATA[5]);
        }
    }

    public static short[] toShortArray(byte[] src) {
        int count = src.length >> 1;
        short[] dest = new short[count];
        for (int i = 0; i < count; i++) {
            dest[i] = (short) (src[i * 2] << 8 | src[2 * i + 1] & 0xff);
        }
        return dest;
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case msg_startconnect:
                    Log.w(TAG, "handleMessage" + " = get commond!");
                    startScanning();
                    break;
                case msg_connectdevice:
                    connectDevice(DEVICE.getAddress());
                    Log.w(TAG, "handleMessage" + " = " + DEVICE.getName());
                    break;
                case msg_disconnecte:
                    bluedatastate = false;
                    disconnectDevice();
                    break;
                case msg_getbluedata:
                    bluedatastate = true;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (bluedatastate){
                                if (mCharacteristic == null){
                                    Log.w(TAG, "run" + " = 启动异常!");
                                }else {
                                    requestCharacteristicValue(mCharacteristic);
                                    Log.w(TAG, "run" + " = 正常启动!");
                                }
                                try {
                                    Thread.sleep(GET_DATA_TIME);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }).start();
                    break;
                case msg_datagetted:
                    Intent intent = new Intent(ACTION_DATA_AVAILABLE);
                    intent.putExtra("rawdata",GESONSOR_DATA);
                    sendBroadcast(intent);
                    break;
                default:
                    break;
            }
        }
    };

    private void regesterReciver(){
        IntentFilter mfilter = new IntentFilter();
        mfilter.addAction(MainActivity.ACTION_DEVICE_CONECT);
        mfilter.addAction(MainActivity.ACTION_DEVICE_DISCONECT);
        registerReceiver(mReciver,mfilter);
    }
    private void unregesterReciver(){
        unregisterReceiver(mReciver);
    }
    private BroadcastReceiver mReciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(MainActivity.ACTION_DEVICE_CONECT)){
                mHandler.sendEmptyMessage(msg_startconnect);
            }else if (action.equals(MainActivity.ACTION_DEVICE_DISCONECT)){
                mHandler.sendEmptyMessage(msg_disconnecte);
            }
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregesterReciver();
        closeDevice();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值