实例介绍
【实例简介】
【实例截图】
【核心代码】
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"); } } } }; }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论