Android 之路60---低功耗蓝牙4.0

导读

1.uses-feature和uses-permission基本知识
2.蓝牙4.0开启,扫描与连接
3.蓝牙4.0通信

uses-feature和uses-permission基本知识

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

蓝牙4.0开启,扫描与连接

这里写图片描述

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hala.bluetoothnew">

    <!--描述本app需要蓝牙功能-->
    <uses-feature android:name="android.hardware.bluetooth.le"
        android:required="true"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <!--手机定位权限-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.hala.bluetoothnew.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="hello"
        android:textSize="20sp"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/scan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="开始扫描"
        app:layout_constraintBottom_toBottomOf="parent" />

    <Button
        android:id="@+id/conn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="连接设备"
        app:layout_constraintBottom_toTopOf="@+id/scan" />

</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.hala.bluetoothnew;

import android.Manifest;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    public static final String TAG="BLESample";
    public static final int BLE_DISCONNECTED=0;
    public static final int BLE_CONNECTING=1;
    public static final int BLE_CONNECTED=2;


    private BluetoothAdapter mBluetoothAdapter;
    private Toast mToast;
    private Button mBtScan;
    private Button mConnect;
    private TextView textView;
    private boolean mIsScanStart=false;
    private BluetoothLeScanner mLeScanner;
    private ScanSettings mScanSettings;
    private String mBleAddress="";

    private Handler mMainUiHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int newState=msg.what;
            if(newState== BluetoothProfile.STATE_CONNECTED){
                mIsConnected=true;
                mConnect.setText("断开");
                showToast("连接成功");
            }else if(newState==BluetoothProfile.STATE_DISCONNECTED){
                mIsConnected=false;
                mConnect.setText("连接");
                showToast("设备已断开");
            }
        }
    };

    private boolean mIsConnected=false;
    private BluetoothGatt mGatt;
    private BluetoothGattCallback mCallback=new BluetoothGattCallback() {
        @Override
        public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
            super.onPhyUpdate(gatt, txPhy, rxPhy, status);
        }

        @Override
        public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
            super.onPhyRead(gatt, txPhy, rxPhy, status);
        }

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            mMainUiHandler.sendEmptyMessage(newState);
        }

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

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

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

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

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
        }

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

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

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


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

        requestPermissions();
        mToast=Toast.makeText(this,"",Toast.LENGTH_LONG);
        final BluetoothManager bluetoothManager=
                (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        //如果手机不支持蓝牙,这个值是空的
        mBluetoothAdapter=bluetoothManager.getAdapter();
        if(mBluetoothAdapter!=null){
            showToast("手机支持蓝牙功能");
        }else {
            finish();
        }

        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
            showToast("手机不支持蓝牙BLE功能");
            finish();
        }else{
            showToast("手机支持蓝牙BLE功能");
        }

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
            mLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
            mScanSettings=new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .setReportDelay(3000).build();
        }

        mBtScan=(Button)findViewById(R.id.scan);
        mBtScan.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
                if(!mIsScanStart){
                    mBtScan.setText("停止扫描");
                    mIsScanStart=true;
                    scan(true);
                }else{
                    mBtScan.setText("开始扫描");
                    mIsScanStart=false;
                    scan(false);
                }
            }
        });

        textView=(TextView)findViewById(R.id.tv);
        mConnect=(Button)findViewById(R.id.conn);
        mConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!mIsScanStart){
                    connect();
                }else{
                    disconnect();
                }
            }
        });

    }

    private boolean connect(){
        final BluetoothDevice device=mBluetoothAdapter.getRemoteDevice(mBleAddress);
        mGatt=device.connectGatt(MainActivity.this,false,mCallback);
        if(mGatt!=null){
            return true;
        }else{
            return false;
        }
    }

    private void disconnect(){
        if(mGatt!=null){
            mGatt.disconnect();
        }
    }


    private void showToast(String msg){
        mToast.setText(msg);
        mToast.show();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void scan(boolean enable){
        final ScanCallback scanCallback=new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                BluetoothDevice device=result.getDevice();
                Log.d(TAG,"name="+device.getName()+"," +
                        "address="+device.getAddress());
                textView.setText(device.getName()+"-"+device.getAddress());
                mBleAddress=device.getAddress();
            }
        };
        if(enable){
            mLeScanner.startScan(scanCallback);
        }else{
            mLeScanner.startScan(scanCallback);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mBluetoothAdapter!=null&&!mBluetoothAdapter.isEnabled()){
            //申请打开蓝牙功能
            Intent enableBtIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(enableBtIntent);
        }
    }

    //动态申请权限
    private void requestPermissions(){
        if(PackageManager.PERMISSION_GRANTED== ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)){

        }else{
            if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION)){

            }else{
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},0);
            }
        }
    }
}

蓝牙4.0通信

其他文件不变

这里写图片描述

这里写图片描述

on.png

这里写图片描述

off.png

这里写图片描述

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.hala.bluetoothnew.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="hello"
        android:textSize="20sp"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_temp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="温度为:"
        android:textSize="20sp"
        app:layout_constraintTop_toBottomOf="@+id/tv" />

    <ImageView
        android:id="@+id/iv_key"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:src="@mipmap/ic_launcher"
        app:layout_constraintBottom_toTopOf="@+id/enable"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_temp" />

    <Button
        android:id="@+id/scan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="开始扫描"
        app:layout_constraintBottom_toBottomOf="parent" />

    <Button
        android:id="@+id/conn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="连接设备"
        app:layout_constraintBottom_toTopOf="@+id/scan" />

    <Button
        android:id="@+id/discovery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="搜寻服务"
        app:layout_constraintBottom_toTopOf="@+id/conn" />

    <Button
        android:id="@+id/enable"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="打开温度传感器"
        app:layout_constraintBottom_toTopOf="@+id/read" />

    <Button
        android:id="@+id/read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="读取温度传感器"
        app:layout_constraintBottom_toTopOf="@+id/discovery" />

</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.hala.bluetoothnew;

import android.Manifest;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    public static final String TAG="BLESample";
    public static final int BLE_DISCONNECTED=0;
    public static final int BLE_CONNECTING=1;
    public static final int BLE_CONNECTED=2;

    private BluetoothGattCharacteristic mSimpleKeyChar;
    //发送按键信息 要查表得到
    private final String SIMPLE_KEY_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb";
    private final String CLIENT_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";

    //温度传感器
    private BluetoothGattCharacteristic mTempConfigChar;
    private BluetoothGattCharacteristic mTempChar;
    private final String IR_TEMPERATURE_UUID = "f000aa01-0451-4000-b000-000000000000";
    private final String IR_TEMPERATURE_CONFIG = "f000aa02-0451-4000-b000-000000000000";



    private BluetoothAdapter mBluetoothAdapter;
    private Toast mToast;
    private Button mBtScan;
    private Button mConnect;
    private Button mDiscovery;
    private Button mEnableTempButton;
    private Button mReadTempButton;
    private TextView textView;
    private TextView mTempTextView;
    private ImageView mKeyImageView;
    private boolean mIsScanStart=false;
    private BluetoothLeScanner mLeScanner;
    private ScanSettings mScanSettings;
    private String mBleAddress="";

    private Handler mMainUiHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int newState=msg.what;
            if(newState== BluetoothProfile.STATE_CONNECTED){
                mIsConnected=true;
                mConnect.setText("断开");
                showToast("连接成功");
            }else if(newState==BluetoothProfile.STATE_DISCONNECTED){
                mIsConnected=false;
                mConnect.setText("连接");
                showToast("设备已断开");
            }
        }
    };

    private int SENSOR_TYPE_SIMPLE_KEY = 0x00;
    private int SENSOR_TYPE_IR_TEMPERATURE = 0x01;

    private Handler mSensorHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int type = msg.what;
            if(type == SENSOR_TYPE_IR_TEMPERATURE) {
                float temp;
                Bundle bundle = msg.getData();
                temp = bundle.getFloat("TEMP");
                mTempTextView.setText("温度为:" + temp);
            } else if(type == SENSOR_TYPE_SIMPLE_KEY) {
                int state = msg.arg1;
                if(state == 0) {
                    mKeyImageView.setImageResource(R.drawable.off);
                } else {
                    mKeyImageView.setImageResource(R.drawable.on);
                }
            }
        }
    };

    private boolean mIsConnected=false;
    private BluetoothGatt mGatt;
    private BluetoothGattCallback mCallback=new BluetoothGattCallback() {
        @Override
        public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
            super.onPhyUpdate(gatt, txPhy, rxPhy, status);
        }

        @Override
        public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
            super.onPhyRead(gatt, txPhy, rxPhy, status);
        }

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            mMainUiHandler.sendEmptyMessage(newState);
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            Log.d(TAG,"onServicesDiscovered");
            discoverGattService(gatt.getServices());
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.d(TAG, "++onCharacteristicRead++");
            byte[] data = characteristic.getValue();
            String value = "";
            for(int i = 0; i < data.length; i++) {
                value += String.format("%02x ", data[i]);
            }
            Log.d(TAG, "value = " + value);
            int byte2 = data[2] & 0xff;
            int byte3 = data[3] & 0xff;
            int rawVal = (byte3 << 8) | byte2;
            float temp = (float)rawVal / 4 * 0.03125f;
            Log.d(TAG, "temp = " + temp);
            Bundle bundle = new Bundle();
            bundle.putFloat("TEMP", temp);
            Message msg = new Message();
            msg.what = SENSOR_TYPE_IR_TEMPERATURE;
            msg.setData(bundle);
            mSensorHandler.sendMessage(msg);
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            Log.d(TAG, "++onCharacteristicWrite++");
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            Log.d(TAG,"onCharacteristicChanged");
            byte[] data = characteristic.getValue();
            String value = "";
            for(int i = 0; i < data.length; i++) {
                value += String.format("%02x ", data[i]);
            }
            Log.d(TAG, "value = " + value);
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
        }

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

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

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

    //用于解析设备中有哪些service
    private void discoverGattService(List<BluetoothGattService> services){
        if(services==null)
            return;
        for(BluetoothGattService service:services){
            String uuid=service.getUuid().toString();
            Log.d(TAG,"Service uuid="+uuid);
            List<BluetoothGattCharacteristic> characteristics
                    =service.getCharacteristics();
            for(BluetoothGattCharacteristic characteristic:characteristics){
                String char_uuid=characteristic.getUuid().toString();
                Log.d(TAG,"charteristic uuid="+char_uuid);
                if(char_uuid.equals(SIMPLE_KEY_UUID)) {
                    Log.d(TAG, "find simple key_on characteristic");
                    mSimpleKeyChar = characteristic;
                    mGatt.setCharacteristicNotification(mSimpleKeyChar, true);
                    BluetoothGattDescriptor descriptor =
                            mSimpleKeyChar.getDescriptor(UUID.fromString(
                                    CLIENT_CONFIG
                            ));
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mGatt.writeDescriptor(descriptor);
                    Log.d(TAG, "enable notification!");
                }else if(char_uuid.equals(IR_TEMPERATURE_CONFIG)) {
                    mTempConfigChar = characteristic;
                    Log.d(TAG, "find temperature config char");
                } else if(char_uuid.equals(IR_TEMPERATURE_UUID)) {
                    mTempChar = characteristic;
                    Log.d(TAG, "find temperature char");
                }

            }
        }
    }

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

        requestPermissions();
        mToast=Toast.makeText(this,"",Toast.LENGTH_LONG);
        final BluetoothManager bluetoothManager=
                (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        //如果手机不支持蓝牙,这个值是空的
        mBluetoothAdapter=bluetoothManager.getAdapter();
        if(mBluetoothAdapter!=null){
            showToast("手机支持蓝牙功能");
        }else {
            finish();
        }

        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
            showToast("手机不支持蓝牙BLE功能");
            finish();
        }else{
            showToast("手机支持蓝牙BLE功能");
        }

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
            mLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
            mScanSettings=new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .setReportDelay(3000).build();
        }

        mBtScan=(Button)findViewById(R.id.scan);
        mBtScan.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
                if(!mIsScanStart){
                    mBtScan.setText("停止扫描");
                    mIsScanStart=true;
                    scan(true);
                }else{
                    mBtScan.setText("开始扫描");
                    mIsScanStart=false;
                    scan(false);
                }
            }
        });

        textView=(TextView)findViewById(R.id.tv);
        mConnect=(Button)findViewById(R.id.conn);
        mConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!mIsScanStart){
                    connect();
                }else{
                    disconnect();
                }
            }
        });

        mDiscovery=(Button)findViewById(R.id.discovery);
        mDiscovery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mGatt!=null){
                    mGatt.discoverServices();
                }
            }
        });

        mEnableTempButton = (Button)findViewById(R.id.enable);
        mEnableTempButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "enable temperature sensor");
                mTempConfigChar.setValue(new byte[] {0x01});
                mGatt.writeCharacteristic(mTempConfigChar);
            }
        });
        mReadTempButton = (Button)findViewById(R.id.read);
        mReadTempButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "read temperature sensor");
                mGatt.readCharacteristic(mTempChar);
            }
        });

        mTempTextView = (TextView)findViewById(R.id.tv_temp);
        mKeyImageView = (ImageView)findViewById(R.id.iv_key);

    }

    private boolean connect(){
        final BluetoothDevice device=mBluetoothAdapter.getRemoteDevice(mBleAddress);
        mGatt=device.connectGatt(MainActivity.this,false,mCallback);
        if(mGatt!=null){
            return true;
        }else{
            return false;
        }
    }

    private void disconnect(){
        if(mGatt!=null){
            mGatt.disconnect();
        }
    }


    private void showToast(String msg){
        mToast.setText(msg);
        mToast.show();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void scan(boolean enable){
        final ScanCallback scanCallback=new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                BluetoothDevice device=result.getDevice();
                Log.d(TAG,"name="+device.getName()+"," +
                        "address="+device.getAddress());
                textView.setText(device.getName()+"-"+device.getAddress());
                mBleAddress=device.getAddress();
            }
        };
        if(enable){
            mLeScanner.startScan(scanCallback);
        }else{
            mLeScanner.startScan(scanCallback);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mBluetoothAdapter!=null&&!mBluetoothAdapter.isEnabled()){
            //申请打开蓝牙功能
            Intent enableBtIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(enableBtIntent);
        }
    }

    //动态申请权限
    private void requestPermissions(){
        if(PackageManager.PERMISSION_GRANTED== ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)){

        }else{
            if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION)){

            }else{
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},0);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37527943/article/details/80205893