基本信息
源码名称:输液报警app源码(基于蓝牙通信)
源码大小:23.07M
文件格式:.rar
开发语言:Java
更新时间:2020-05-07
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍


package com.tianguang.my.drip;

import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.PersistableBundle;
import android.os.Handler;
import android.os.Message;

import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
 * Created by my on 2018/11/12.
 */

public class Drip extends AppCompatActivity  {
    //实现连接BLE,发送和接受BLE的数据
    //private final static String TAG = HandActivity.class.getSimpleName();

    private TextView pose,drip,hand_connect,title;
    private CheckBox lings,zhengd;
    private Button btnExit,btnOpen,btnClose;
    private ImageView img_1,img_2;
    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
    private static final String TAG = "message";

    static long recv_cnt = 0;

    private String mDeviceName;
    private String mDeviceAddress;
    private BluetoothLeService mBluetoothLeService;
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
            new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    private boolean mConnected = false;
    private Vibrator vibrator;
    private SoundPool soundPool;
    int streamID_1;
    int soundID_1;
    int num=0;
    int count=0;
    double right=0.00f;
    boolean flag=false;
    private final String LIST_NAME = "NAME";
    private final String LIST_UUID = "UUID";
    private long recvBytes=0;
    private long lastSecondBytes=0;
    private long sendBytes;
    private StringBuilder mData;

    int sendIndex = 0;
    int sendDataLen=0;
    byte[] sendBuf;
    /**时间数据*/
    Date[] xcache = new Date[100];
    /**数据*/
    int[] ycache = new int[100];
    /*******蓝牙******/
    private String smsg="";
    public static final int RECV_VIEW = 0;
    private static final String ARG_SECTION_NUMBER = "section_number";
    String message;

    int length=20;
    //               包头
    int[] sendVal={0xfe,0xa0,0,0,0xff};//发送缓冲区 包头,振动占空比,频率,电脉冲点空比,频率,红外,FE,高压,低压,心率,校验位,包尾
    public static  boolean isRecording = true;// 线程控制标记
    public static boolean osc_flag=true;
    public static boolean dian_flag=true;
    public static boolean red_flag=true;
    // private String encodeType = "GBK";
    private String encodeType = "UTF-8";
    private String readStr1;
    byte[] buf={0};

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.drip);
       TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("床号101");
       tv_title.setGravity(Gravity.CENTER);


        setTitle("床号101");
        //获取蓝牙的名字和地址
        final Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
        //Toast.makeText(getApplication(),mDeviceName,Toast.LENGTH_LONG).show();
        init_view();
        //init_chart();
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //
                finish();
                onDestroy();
            }
        });
    }
    public void init_view(){
        drip= (TextView) findViewById(R.id.drip);
        hand_connect=(TextView) findViewById(R.id.connect);
        img_1= (ImageView) findViewById(R.id.img_1);
        img_2= (ImageView) findViewById(R.id.img_2);
        pose= (TextView) findViewById(R.id.liang);
        vibrator = (Vibrator)this.getSystemService(this.VIBRATOR_SERVICE);//振动
        lings= (CheckBox) findViewById(R.id.lings);
        zhengd= (CheckBox) findViewById(R.id.zhengd);
        soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
        soundID_1=soundPool.load(getApplicationContext(), R.raw.cnwav, 1);
        btnExit= (Button) findViewById(R.id.btnExit);
    }
    public void onDestroy() {
        //当结束程序时关掉Timer
        super.onDestroy();
        //timer.cancel();
        unbindService(mServiceConnection);
        mBluetoothLeService = null;
        soundPool.release();
    };
    @Override
    protected void onResume() {
        super.onResume();
        //绑定广播接收器
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            Log.d(TAG, "Connect request result="   result);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
    }
    private void updateConnectionState(final int resourceId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // mConnectionState.setText(resourceId);
            }
        });
    }

    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_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_WRITE_SUCCESSFUL);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_NO_DISCOVERED);
        return intentFilter;
    }
    private byte[] stringToBytes(String s) {
        byte[] buf = new byte[s.length() / 2];
        for (int i = 0; i < buf.length; i  ) {
            try {
                buf[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2   2), 16);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return buf;
    }
    int check_number(int[] txbuf , int leng)
    {
        int checksum;
        int middlevar;
        checksum=0;
        for(int i=0;i<leng;i  )
        {
            middlevar=txbuf[i];
            checksum=checksum^ middlevar;
        }
        return checksum;
    }
    public String bytesToString(byte[] bytes) {
        final char[] hexArray = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[bytes.length * 2];
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i  ) {
            int v = bytes[i] & 0xFF;
            hexChars[i * 2] = hexArray[v >>> 4];
            hexChars[i * 2   1] = hexArray[v & 0x0F];

            sb.append(hexChars[i * 2]);
            sb.append(hexChars[i * 2   1]);
            sb.append(' ');
        }
        return sb.toString();
    }
    //    private void displayData(byte[] buff) {
//        recvBytes  = buff.length;
//        recv_cnt  = buff.length;
//
//        for(int i =0;i<buff.length;i  )
//            buf[i]=buff[i];
//        runOnUiThread(new Runnable() {
//            @Override
//           public void run() {
//                String str = bytesToString(buf);
//                //str = str.substring(0, 34);
//                bluetext.setText(str   " ");
//
//                //if ((buf[0] == -1) && (buf[13] == -3)) {
//                    //String str = bytesToString(buf);
//                    //str = str.substring(0, 34);
//                    //bluetext.setText(str   " ");
//                    pose.setText(Integer.toString(buf[6]) "." Integer.toString(buf[7]));
//                    setLimitImage1(buf[1]);
//                    setLimitImage2(buf[2]);
//                    setLimitImage3(buf[3]);
//                    setLimitImage4(buf[4]);
//               // }
//            }
//        });
//    }

    private void displayData(byte[] buf) {
        recvBytes  = buf.length;
        recv_cnt  = buf.length;
        String s = bytesToString(buf);
        //img_1.setImageResource(R.drawable.red);
        //以下是学生单片机蓝牙实验代码
    /*    if (buf.length!=5) {
            return;
        }
        if (buf[4] == -1&&buf[0]==-2) {
            drip.setText(Integer.toString(buf[1]));
            pose.setText(Integer.toString(buf[2]));
        }*/
           // 以下是点滴的程序
        if (buf.length!=1) {
            return;
        }
        if (buf[0]==-2)
        {
            num  ;
            if(num==2)
            {
                count=0;
            }
        }
            if (buf[0] == -1) {
                img_1.setImageResource(R.drawable.red);
                img_2.setImageResource(R.drawable.gray);
                if (zhengd.isChecked()) {
                    vibrator.vibrate(1000);
                }
                else
                {
                    vibrator.cancel();
                }
                if (lings.isChecked())
                {
                        streamID_1 = soundPool.play(soundID_1, 0.8f, 0.8f, 1, -1, 1.0f);
                }
                else {
                    soundPool.pause(streamID_1);
                    soundPool.stop(streamID_1);
                }
                drip.setText("---");
                pose.setText("---");
            } else {
                img_2.setImageResource(R.drawable.green);
                img_1.setImageResource(R.drawable.gray);
                if(buf[0]!=0) {
                    drip.setText(Integer.toString(3000 / (buf[0] & 0xff)));
                    count  ;
                    right=count*0.05;
                    DecimalFormat df = new DecimalFormat("0.00");
                    message = df.format(right);
                    pose.setText(message);//Double.toString(0.05f*count)
                }
                vibrator.cancel();
                soundPool.pause(streamID_1);
                soundPool.stop(streamID_1);
                //soundPool.release();
                //pose.setText(Integer.toString(0.05*));
           }
    }
    private void onSendBtnClicked() {
        final byte[] buf = new byte[5];
        for (int i=0;i<5;i  )
        {
            buf[i] = (byte) sendVal[sendIndex i];
        }
        mBluetoothLeService.writeData(buf);
    }
    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up initialization.
            mBluetoothLeService.connect(mDeviceAddress);
        }

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

    // Handles various events fired by the Service.
    // ACTION_GATT_CONNECTED: connected to a GATT server.
    // ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
    // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
    // ACTION_DATA_AVAILABLE: received data from the device.  This can be a result of read
    //                        or notification operations.
    //广播接收器,负责接收BluetoothLeService类发送的数据
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                 hand_connect.setText("设置蓝牙设备名-已连接");
                count=0;
                //System.out.println("1");
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected = false;
                 hand_connect.setText("设置蓝牙设备名-未连接");
                //System.out.println("2");
                //updateConnectionState(R.string.disconnected);
                //invalidateOptionsMenu();
                mBluetoothLeService.connect(mDeviceAddress);
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {////发现GATT服务器
                //特征值找到才代表连接成功
                mConnected = true;
                hand_connect.setText("设置蓝牙设备名-已连接");
                count=0;
               // System.out.println("3");
                //invalidateOptionsMenu();
                //updateConnectionState(R.string.connected);
            }else if (BluetoothLeService.ACTION_GATT_SERVICES_NO_DISCOVERED.equals(action)){
                mBluetoothLeService.connect(mDeviceAddress);
            }else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
//                final byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
//                for (int i = 0; i < data.length; i  ) {
//                    System.out.println("data......"   data[i]);
//                }
//                final StringBuilder stringBuilder = new StringBuilder();
//                 for(byte byteChar : data)
//                      stringBuilder.append(String.format("%02X ", byteChar));
//                Log.e("-----------------",">>>" stringBuilder.toString());
                //Log.v("log",stringBuilder.toString());
                hand_connect.setText("设置蓝牙设备名-接收到数据");
               // System.out.println("4");
                displayData(intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA));
            }else if (BluetoothLeService.ACTION_WRITE_SUCCESSFUL.equals(action)) {
                //mSendBytes.setText(sendBytes   " ");
                if (sendDataLen>0)
                {
                    Log.v("log","Write OK,Send again");
                    onSendBtnClicked();
                }
                else {
                    Log.v("log","Write Finish");
                }
            }

        }
    };

}