蓝牙连接和通过蓝牙获取设备数据

package com.skinod.clocfit.ui.activity;

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.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.skinod.clocfit.R;
import com.skinod.clocfit.bean.MyDevicesBodyTemperatureBrightScreenHelper;
import com.skinod.clocfit.ui.dialog_gather.PromptDialog;
import com.skinod.clocfit.utils.DBHelper;
import com.skinod.clocfit.utils.L;
import com.yc.pedometer.utils.GetFunctionList;
import com.yc.pedometer.utils.GlobalVariable;
import com.yc.pedometer.utils.LogUtils;

import java.io.OutputStream;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.UUID;

public class MainActivity2 extends AppCompatActivity {
    private PromptDialog promptDialog;

    //蓝牙设备的Service的UUID
   // public final static UUID UUID_SERVICE = UUID.fromString("000000ff-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_SERVICE = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
   // public final static UUID UUID_SERVICE = UUID.fromString("000055ff-0000-1000-8000-00805f9b34fb");
    //蓝牙设备的notify的UUID
    public final static UUID UUID_NOTIFY = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");
//    public final static UUID UUID_NOTIFY = UUID.fromString("000033f2-0000-1000-8000-00805f9b34fb");
    private BluetoothGatt mBluetoothGattOne;
    private String TypeValue;
    private Context context;
//    private DataBaseHepler DBHelper;
    private DBHelper dbHelper;
    private boolean aBoolean1=true;
    private TextView tv;
    private SQLiteDatabase db;
    private ContentValues values;
    private  BluetoothDevice bluetoothDeviceOne;
    private  Long timeDifference;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                Log.d("输出d2","关闭成功");
                break;
            }
        }
    };

    private OutputStream mOutputStream;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        promptDialog = new PromptDialog(this);
        if (aBoolean1) {
            promptDialog.getDefaultBuilder().touchAble(false).round(3).loadingDuration(3000);
            promptDialog.showSuccess("连接成功");
            promptDialog.dismissImmediately();
            promptDialog.dismiss();
            aBoolean1=false;
            Log.d("输出d","成功");
        }

        //获取BluetoothManager
        BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        //获取BluetoothAdapter
        BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();

        //如果蓝牙没有打开 打开蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
      //  BluetoothDevice bluetoothDeviceOne = mBluetoothAdapter.getRemoteDevice("78:02:B2:39:55:D2");
        bluetoothDeviceOne = mBluetoothAdapter.getRemoteDevice("70:87:9E:A1:86:29");
        //如果Gatt在运行,将其关闭
        if (mBluetoothGattOne != null) {
            mBluetoothGattOne.close();
            mBluetoothGattOne = null;
        }

        //连接蓝牙设备并获取Gatt对象
        mBluetoothGattOne = bluetoothDeviceOne.connectGatt(this, true, bluetoothGattCallbackOne);
        context = getApplicationContext();
        Log.d("输出a1a",""+bluetoothDeviceOne.getUuids());
        if (GetFunctionList.isSupportFunction_Fifth(context, GlobalVariable.IS_SUPPORT_TEMPERATURE_TEST)) {

        } else {
//            Toast.makeText(context, "R.string.not_support_body_temperature",
//                    Toast.LENGTH_SHORT).show();
        }

        tv = findViewById(R.id.tv_d);

        //new出数据库,(上下文,版本号)
      //  dbHelper = new DBHelper(this,4);

        MyDevicesBodyTemperatureBrightScreenHelper dbHelper = new MyDevicesBodyTemperatureBrightScreenHelper(MainActivity2.this,
                "BookStore3.db", null, 4);//版本号
        db = dbHelper.getWritableDatabase();
        //插入
        values  =new ContentValues();

        Calendar cal=Calendar.getInstance();
        int y=cal.get(Calendar.YEAR);
        int m=cal.get(Calendar.MONTH);
        int dd=cal.get(Calendar.DATE);
        int h=cal.get(Calendar.HOUR_OF_DAY);
        int mi=cal.get(Calendar.MINUTE);
        int s=cal.get(Calendar.SECOND);
        //   String dateFormat = "现在时刻是"+y+"年"+m+"月"+dd+"日"+h+"时"+mi+"分"+s+"秒";
        String dateFormat = ""+y+"-"+m+"-"+dd;
        String dateMonth = ""+y+"-"+m;
        timeDifference = cal.getTimeInMillis()-getTodayStartTime();
        Log.d("输出啊", "--"+mi +getTodayStartTime()+"-" +cal.getTimeInMillis()+"--"+timeDifference);
                插入
//        values.put("temperature",37.1);
//        values.put("time",""+550);
//        values.put("date",""+"2021-12-05");
//        values.put("month",""+"2021-12");
//        //  values.put("id",0);
//        db.insert("Books",null,values);
//                查询
        Cursor cursor = db.query("Books",null,null,null,null,null,null);
        if (cursor.moveToFirst()) {
            do {
              //查询条件
                while (cursor.moveToNext()){
                    int titleIndex = cursor.getColumnIndex("temperature");
                    int titleIndex2 = cursor.getColumnIndex("time");
                    int titleIndex3 = cursor.getColumnIndex("date");
                    String title = cursor.getString(titleIndex);
                    String title2 = cursor.getString(titleIndex2);
                    String title3 = cursor.getString(titleIndex3);
                    Log.d("TAGaa","name"+title+"---"+title2+"--"+title3);
                }
            }while(cursor.moveToNext());
        }





        //修改数据
//        String updateReceiver = "13";
//        values.put("time","2");
//        db.update(
//                "Books",
//                values,
//                "time",
//                new String[]{updateReceiver}
//
//        );
//        Toast.makeText(getApplication(),"修改成功!",Toast.LENGTH_SHORT).show();

      //  deleteDatabase("BookStore3.db");//删除数据库
       // db.close();
        byte[] b = new byte[]{(byte)0x7E,(byte)0x02,(byte)0x21,(byte) 0x11};

        new Thread(new Runnable() {
            @Override
            public void run() {
                OutputStream os = null;
                Log.d("输出d","关闭成功");
                try {

//                    BluetoothSocket socket = bluetoothDeviceOne.createRfcommSocketToServiceRecord(UUID_NOTIFY);
//                    socket.connect();
//                    os = socket.getOutputStream();
//                    os.write(b);
//                    os.flush();
                    Message msg =new Message();
                    msg.what = 0;
                    mHandler.sendMessage(msg);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        query("2021-12-06","2021-12-07");


//        values.put("temperature",36.2);
//        values.put("time",""+420);
//        values.put("date",""+"2021-12-05");
//        //  values.put("id",0);
//        db.insert("Books",null,values);

    }

    public Cursor query(String str1, String str2){  //str1 str2分别是区间的下限2000-01-01和上限2000-02-25
        String[] whereArgs={str1, str2};
        Cursor c = db.query("Books", null, "date between ? and ?",whereArgs, null, null, null);
        do {
            //查询条件
            while (c.moveToNext()){
                int titleIndex = c.getColumnIndex("temperature");
                int titleIndex2 = c.getColumnIndex("time");
                int titleIndex3 = c.getColumnIndex("date");
                String title = c.getString(titleIndex);
                String title2 = c.getString(titleIndex2);
                String title3 = c.getString(titleIndex3);
                Log.d("TAGaa2","name"+title+"---"+title2+"--"+title3);

                Log.d("输出ad",""+"-"+titleIndex+"-"+""+titleIndex2+"-"+titleIndex3+"-")  ;
            }
        }while(c.moveToNext());


        return c;
    }


    /**
     * 第一个设备  蓝牙返回数据函数
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private BluetoothGattCallback bluetoothGattCallbackOne = new BluetoothGattCallback() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    L.d("设备一连接成功");

                    //搜索Service
                    gatt.discoverServices();
                    aBoolean1=false;

                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    L.d("设备一连接断开");
                }
            }
            super.onConnectionStateChange(gatt, status, newState);
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            //根据UUID获取Service中的Characteristic,并传入Gatt中
            BluetoothGattService bluetoothGattService = gatt.getService(UUID_SERVICE);
            BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(UUID_NOTIFY);

            for(BluetoothGattDescriptor dp:bluetoothGattCharacteristic.getDescriptors()){
                dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                gatt.writeDescriptor(dp);
            }
            boolean isConnect = gatt.setCharacteristicNotification(bluetoothGattCharacteristic, true);
            if (isConnect){
                Log.i("geanwen", "onServicesDiscovered: 设备一连接notify成功");

                Intent intent = new Intent(MainActivity2.this,HomeBodyTemperatureActivity.class);
                startActivity(intent);
            }else {
                Log.i("geanwen", "onServicesDiscovered: 设备一连接notify失败");
            }
            super.onServicesDiscovered(gatt, status);
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {//数据改变
            super.onCharacteristicChanged(gatt, characteristic);
//            String data = new String(characteristic.getValue());

            Log.i("geanwen", "onCharacteristicChanged: " + characteristic.getValue());
            Log.d("da","5");
            byte[] var8;
            byte[] var10000 = var8 = characteristic.getValue();
            StringBuilder var3 = null;
            if (var10000 != null && var8.length > 0) {
                var3 = new StringBuilder(var8.length);
                int var4 = var8.length;
                for(int var5 = 0; var5 < var4; ++var5) {
                    byte var6 = var8[var5];
                    Object[] var7;
                    (var7 = new Object[1])[0] = var6;
                    var3.append(String.format("%02X", var7));
                }
            }
                if (characteristic.getUuid().equals(UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"))) {
                    MainActivity2.this.a(var3, var8);
                } else if (characteristic.getUuid().equals(UUID.fromString("000034f2-0000-1000-8000-00805f9b34fb"))) {
                    if (TextUtils.isEmpty(var3)) {
                        return;
                    }
                    //  MainActivity2.this.b(var3, var8);
                }
        }
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // 发送成功

            } else {
                // 发送失败
            }
        }

    };
    private void a(StringBuilder var1, byte[] var2){
        String var3 = var1.toString().substring(0, 2);
        String var4 = "";
        if (var1.toString().length() >= 4) {
            var4 = var1.toString().substring(0, 4);
        }
        String var5 = "";
        String var6 = "";
        int var7 = var1.toString().length();
        LogUtils.i("MainActivity", "BLE---->APK =" + var1);
        TypeValue =var1.toString();
        String valid =TypeValue.substring(2,3);
        Log.d("输出的",""+valid);
        if (valid.equals("1") ) {
            Log.d("输出","无效");
        }else {
            String BodyTemperature  =TypeValue.substring(6,7);//判断是华氏度还是摄氏度1\0
            String temperature =TypeValue.substring(8,12);//温度
            if (BodyTemperature.equals( "0")) {//摄氏度
                int d = Integer.valueOf(temperature,16);   //d=255 十六进制转十进制
                double RealTimeTemperature = d*0.1;//体温
                String RealTimeTemperature2 = String.format("%.1f", RealTimeTemperature);


                Calendar cal=Calendar.getInstance();
                int y=cal.get(Calendar.YEAR);
                int m=cal.get(Calendar.MONTH);
                int dd=cal.get(Calendar.DATE);
                int h=cal.get(Calendar.HOUR_OF_DAY);
                int mi=cal.get(Calendar.MINUTE);
                int s=cal.get(Calendar.SECOND);
                String dateFormat = "现在时刻是"+y+"年"+m+"月"+dd+"日"+h+"时"+mi+"分"+s+"秒";
                timeDifference = cal.getTimeInMillis()-getTodayStartTime();
                Log.d("输出啊", RealTimeTemperature2+"--"+mi +getTodayStartTime()+"-" +cal.getTimeInMillis()+"--"+timeDifference);


//                插入
                values.put("temperature",RealTimeTemperature2);
                values.put("time",""+timeDifference/3600000*60);
                values.put("date",""+"2021-12-06");
              //  values.put("id",0);
                db.insert("Books",null,values);
//                查询
                Cursor cursor = db.query("Books",null,null,null,null,null,null);
                if (cursor.moveToFirst()) {
                    do {
                       //查询条件
                        // Log.d("TAGa","name"+pages);
                        while (cursor.moveToNext()){
                            int titleIndex = cursor.getColumnIndex("temperature");
                            int titleIndex2 = cursor.getColumnIndex("time");
                            int titleIndex3 = cursor.getColumnIndex("date");
                            String title = cursor.getString(titleIndex);
                            String title2 = cursor.getString(titleIndex2);
                            String title3 = cursor.getString(titleIndex3);
                            //   Toast.makeText(getApplication(),title+"---"+title2,Toast.LENGTH_SHORT).show();
                            Log.d("TAGa","name"+title+"---"+title2+"-"+title3);
                        }
                    }while(cursor.moveToNext());
                }



            }else {//华氏度
                String ss2 =TypeValue.substring(8,12);
            }
        }
        if (var1.length() > 2) {
            var5 = var1.toString().substring(2, 4);
            if (var7 == 8) {
                var6 = var1.toString().substring(0, var7 - 2);
            }
        }
    }

    public static long getTodayStartTime() {
        //设置时区
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Long time1 = System.currentTimeMillis();  //获取当前时间戳(精确到毫秒)

        return calendar.getTimeInMillis();

    }




    @Override
    public void onDestroy() {
        super.onDestroy();
        db.close();
}
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信工院李平

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值