基本信息
源码名称:Android 蓝牙连接,解决数据报文分段 实例源码
源码大小:7.82M
文件格式:.zip
开发语言:Java
更新时间:2014-08-29
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
package com.forward.bluetooth; import java.text.DecimalFormat; import android.annotation.SuppressLint; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.forward.bluetooth.bluetooth.BluetoothCommService; import com.forward.bluetooth.bluetooth.BluetoothEnvironment; import com.forward.bluetooth.bluetooth.ConstantsBluetooth; import com.forward.bluetooth.bluetooth.ScanBTDeviceActivity; import com.forward.bluetooth.bluetooth.data.Datagram; public class MainActivity extends Activity { private TextView tvSpeed1, tvSpeed2, tvSpeed3, tvSpeed4, tvSpeed5, tvSpeed6; private ImageView imgSpeed1 = null, imgSpeed2 = null, imgSpeed3 = null, imgSpeed4 = null, imgSpeed5 = null, imgSpeed6 = null; private ImageView imgDirectionArrow1, imgDirectionArrow2 = null; private TextView tvDirection1, tvDirection2; private ImageView imgTemperature = null, imgTemperaturePilar = null, imgHumidity = null, imgHumidityPilar = null, imgPressure = null, imgPressurePointer = null; private TextView tvTemperature, tvHumidity, tvPressure; private RotateAnimation animSpeed1, animSpeed2, animSpeed3, animSpeed4, animSpeed5, animSpeed6; private RotateAnimation animDirection1, animDirection2; private ScaleAnimation animTemperature, animHumidity; private RotateAnimation animPressure; private float currentDirection1 = 0, currentDirection2 = 0, currentTemperature = ConstantsEwins.MIN_TEMPERATURE_Y, currentHumidity = 0.0f, currentPressure = 0; DecimalFormat df = new DecimalFormat("0.00"); private ImageButton btnOpenBT = null; private TextView tvDeviceName = null; private Datagram datagram = new Datagram(); private BluetoothAdapter btAdapter; private BluetoothDevice mDevice; private int[] checked = new int[11]; private long exitTime = 0;// 用于再按一次退出 @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getBluetoothAdapter(); findAllControls(); initAnimations(); } private void findAllControls() { imgSpeed1 = (ImageView) findViewById(R.id.imgSpeed1); imgSpeed2 = (ImageView) findViewById(R.id.imgSpeed2); imgSpeed3 = (ImageView) findViewById(R.id.imgSpeed3); imgSpeed4 = (ImageView) findViewById(R.id.imgSpeed4); imgSpeed5 = (ImageView) findViewById(R.id.imgSpeed5); imgSpeed6 = (ImageView) findViewById(R.id.imgSpeed6); tvSpeed1 = (TextView) findViewById(R.id.tvSpeed1); tvSpeed2 = (TextView) findViewById(R.id.tvSpeed2); tvSpeed3 = (TextView) findViewById(R.id.tvSpeed3); tvSpeed4 = (TextView) findViewById(R.id.tvSpeed4); tvSpeed5 = (TextView) findViewById(R.id.tvSpeed5); tvSpeed6 = (TextView) findViewById(R.id.tvSpeed6); imgDirectionArrow1 = (ImageView) findViewById(R.id.imgDirectionArrow1); imgDirectionArrow2 = (ImageView) findViewById(R.id.imgDirectionArrow2); tvDirection1 = (TextView) findViewById(R.id.tvDirection1); tvDirection2 = (TextView) findViewById(R.id.tvDirection2); imgTemperature = (ImageView) findViewById(R.id.imgTemperature); imgTemperaturePilar = (ImageView) findViewById(R.id.imgTemperaturePilar); imgHumidity = (ImageView) findViewById(R.id.imgHumidity); imgHumidityPilar = (ImageView) findViewById(R.id.imgHumidityPilar); imgPressure = (ImageView) findViewById(R.id.imgPressure); imgPressurePointer = (ImageView) findViewById(R.id.imgPressurePointer); tvTemperature = (TextView) findViewById(R.id.tvTemperature); tvHumidity = (TextView) findViewById(R.id.tvHumidity); tvPressure = (TextView) findViewById(R.id.tvPressure); btnOpenBT = (ImageButton) findViewById(R.id.btnOpenBT); btnOpenBT.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(MainActivity.this, ScanBTDeviceActivity.class); startActivityForResult(intent, ConstantsBluetooth.REQUEST_CONNECT_DEVICE); } }); tvDeviceName = (TextView) findViewById(R.id.tvDeviceName); for (int i = 0; i < 11; i ) checked[i] = View.VISIBLE; } private void initAnimations() { animSpeed1 = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animSpeed1.setInterpolator(new LinearInterpolator()); animSpeed1.setRepeatCount(-1); animSpeed1.setFillAfter(true); animSpeed2 = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animSpeed2.setInterpolator(new LinearInterpolator()); animSpeed2.setRepeatCount(-1); animSpeed2.setFillAfter(true); animSpeed3 = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animSpeed3.setInterpolator(new LinearInterpolator()); animSpeed3.setRepeatCount(-1); animSpeed3.setFillAfter(true); animSpeed4 = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animSpeed4.setInterpolator(new LinearInterpolator()); animSpeed4.setRepeatCount(-1); animSpeed4.setFillAfter(true); animSpeed5 = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animSpeed5.setInterpolator(new LinearInterpolator()); animSpeed5.setRepeatCount(-1); animSpeed5.setFillAfter(true); animSpeed6 = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animSpeed6.setInterpolator(new LinearInterpolator()); animSpeed6.setRepeatCount(-1); animSpeed6.setFillAfter(true); } private void getBluetoothAdapter() { btAdapter = BluetoothAdapter.getDefaultAdapter(); if (btAdapter == null) { Toast.makeText(MainActivity.this, "本设备不支持蓝牙", Toast.LENGTH_SHORT).show(); finish(); return; } while (!btAdapter.isEnabled()) { if (btAdapter.enable()) { Toast.makeText(MainActivity.this, "蓝牙已经启动", Toast.LENGTH_SHORT).show(); break; } else { Toast.makeText(MainActivity.this, "蓝牙启动失败", Toast.LENGTH_SHORT).show(); return; } } if (btAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(intent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, 1, 0, R.string.tianjiachuanganqi); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getOrder() == 0) { Intent intent = new Intent(MainActivity.this, AddDeleteSensorsActivity.class); intent.putExtra("checked", checked); startActivityForResult(intent, ConstantsEwins.REQUEST_ADDDELETE_SENSORS); } return super.onOptionsItemSelected(item); } @Override protected void onResume() { System.out.println("------- ON RESUME ---------"); super.onResume(); if (BluetoothEnvironment.service != null) { if (btAdapter.isEnabled() && BluetoothEnvironment.service.getState() == ConstantsBluetooth.STATE_NONE) { BluetoothEnvironment.service.start(); } BluetoothEnvironment.service.setHandler(mHandler, null); } else { BluetoothEnvironment.service = new BluetoothCommService(this, mHandler, null); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case ConstantsBluetooth.REQUEST_CONNECT_DEVICE: if (resultCode == RESULT_OK) { String address = data.getExtras().getString(ConstantsBluetooth.DEVICE_ADDRESS); mDevice = btAdapter.getRemoteDevice(address); if (mDevice == null) return; if (BluetoothEnvironment.service != null) BluetoothEnvironment.service.connect(mDevice); } break; case ConstantsEwins.REQUEST_ADDDELETE_SENSORS: if (resultCode == RESULT_OK) { checked = data.getExtras().getIntArray("checked"); if (View.INVISIBLE == checked[0]) imgSpeed1.clearAnimation(); imgSpeed1.setVisibility(checked[0]); tvSpeed1.setVisibility(checked[0]); if (View.INVISIBLE == checked[1]) imgSpeed2.clearAnimation(); imgSpeed2.setVisibility(checked[1]); tvSpeed2.setVisibility(checked[1]); if (View.INVISIBLE == checked[2]) imgSpeed3.clearAnimation(); imgSpeed3.setVisibility(checked[2]); tvSpeed3.setVisibility(checked[2]); if (View.INVISIBLE == checked[3]) imgSpeed4.clearAnimation(); imgSpeed4.setVisibility(checked[3]); tvSpeed4.setVisibility(checked[3]); if (View.INVISIBLE == checked[4]) imgSpeed5.clearAnimation(); imgSpeed5.setVisibility(checked[4]); tvSpeed5.setVisibility(checked[4]); if (View.INVISIBLE == checked[5]) imgSpeed6.clearAnimation(); imgSpeed6.setVisibility(checked[5]); tvSpeed6.setVisibility(checked[5]); if (View.INVISIBLE == checked[6]) imgDirectionArrow1.clearAnimation(); imgDirectionArrow1.setVisibility(checked[6]); tvDirection1.setVisibility(checked[6]); if (View.INVISIBLE == checked[7]) imgDirectionArrow2.clearAnimation(); imgDirectionArrow2.setVisibility(checked[7]); tvDirection2.setVisibility(checked[7]); if (View.INVISIBLE == checked[8]) imgTemperaturePilar.clearAnimation(); imgTemperature.setVisibility(checked[8]); imgTemperaturePilar.setVisibility(checked[8]); tvTemperature.setVisibility(checked[8]); if (View.INVISIBLE == checked[9]) imgHumidityPilar.clearAnimation(); imgHumidity.setVisibility(checked[9]); imgHumidityPilar.setVisibility(checked[9]); tvHumidity.setVisibility(checked[9]); if (View.INVISIBLE == checked[10]) imgPressurePointer.clearAnimation(); imgPressure.setVisibility(checked[10]); imgPressurePointer.setVisibility(checked[10]); tvPressure.setVisibility(checked[10]); } break; default: break; } } @SuppressLint("HandlerLeak") private final Handler mHandler = new Handler() { int length = 0; boolean firstReceived = true; long lastReadTime = System.currentTimeMillis(); StringBuffer sb = new StringBuffer(ConstantsEwins.DATA_LENGTH); @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case ConstantsBluetooth.MESSAGE_STATE_CHANGE: switch (msg.arg1) { case ConstantsBluetooth.STATE_CONNECTED: Toast.makeText(MainActivity.this, "已连接至" msg.obj "!!fdasfds", Toast.LENGTH_SHORT).show(); tvDeviceName.setText((String) msg.obj); btnOpenBT.setBackgroundResource(R.drawable.bluetooth_on); break; case ConstantsBluetooth.STATE_CONNECTING: Toast.makeText(MainActivity.this, "正在连接,请稍候", Toast.LENGTH_LONG).show(); break; case ConstantsBluetooth.STATE_LISTEN: if (ConstantsBluetooth.CONNECTION_FAILED.equals(msg.obj)) { Toast.makeText(MainActivity.this, "连接不成功", Toast.LENGTH_SHORT).show(); btnOpenBT.setBackgroundResource(R.drawable.bluetooth_off); } else if (ConstantsBluetooth.CONNECTION_LOST.equals(msg.obj)) { Toast.makeText(MainActivity.this, "连接丢失", Toast.LENGTH_SHORT).show(); btnOpenBT.setBackgroundResource(R.drawable.bluetooth_off); } break; case ConstantsBluetooth.STATE_NONE: btnOpenBT.setBackgroundResource(R.drawable.bluetooth_off); break; } break; case ConstantsBluetooth.MESSAGE_WRITE: // byte[] writeBuf = (byte[]) msg.obj; break; case ConstantsBluetooth.MESSAGE_READ: if (firstReceived) lastReadTime = System.currentTimeMillis(); // System.out.println("lastReadTime:" lastReadTime); firstReceived = false; if (System.currentTimeMillis() - lastReadTime > ConstantsEwins.DATAGRAM_INTERVAL) { // System.out.println("超过500毫秒的数据" sb.toString() "长度为" // length); if (length == ConstantsEwins.DATAGRAM_BYTES_LENGTH) { datagram.parseDatagram(sb.toString()); modifyViews(); } sb = new StringBuffer(ConstantsEwins.DATA_LENGTH); length = 0; } String data = (String) msg.obj; System.out.println("接收到的数据:" data); length = msg.arg1; sb.append(data); lastReadTime = System.currentTimeMillis(); break; } } }; @SuppressLint("NewApi") private void modifyViews() { tvSpeed1.setText("风速1: " df.format(datagram.getSpeed1()) " m/s"); tvSpeed2.setText("风速2: " df.format(datagram.getSpeed2()) " m/s"); tvSpeed3.setText("风速3: " df.format(datagram.getSpeed3()) " m/s"); tvSpeed4.setText("风速4: " df.format(datagram.getSpeed4()) " m/s"); tvSpeed5.setText("风速5: " df.format(datagram.getSpeed5()) " m/s"); tvSpeed6.setText("风速6: " df.format(datagram.getSpeed6()) " m/s"); tvDirection1.setText("风向1: " (datagram.getDirection1() - (datagram.getDirection1() / 360) * 360) "°"); tvDirection2.setText("风向2: " (datagram.getDirection2() - (datagram.getDirection2() / 360) * 360) "°"); tvTemperature.setText("温度: " df.format(datagram.getTemperature()) " ℃"); tvHumidity.setText("湿度: " datagram.getHumidity() " %"); tvPressure.setText("气压: " df.format(datagram.getPressure()) " kPa"); // 风速改变 long newDuration; newDuration = calcSpeedDuration(datagram.getSpeed1()); if (animSpeed1.getDuration() != newDuration) { animSpeed1.setDuration(newDuration); if (View.INVISIBLE != imgSpeed1.getVisibility()) { imgSpeed1.clearAnimation(); imgSpeed1.startAnimation(animSpeed1); } } newDuration = calcSpeedDuration(datagram.getSpeed2()); if (animSpeed2.getDuration() != newDuration) { animSpeed2.setDuration(newDuration); if (View.INVISIBLE != imgSpeed2.getVisibility()) { imgSpeed2.clearAnimation(); imgSpeed2.startAnimation(animSpeed1); } } newDuration = calcSpeedDuration(datagram.getSpeed3()); if (animSpeed3.getDuration() != newDuration) { animSpeed3.setDuration(newDuration); if (View.INVISIBLE != imgSpeed3.getVisibility()) { imgSpeed3.clearAnimation(); imgSpeed3.startAnimation(animSpeed3); } } newDuration = calcSpeedDuration(datagram.getSpeed4()); if (animSpeed4.getDuration() != newDuration) { animSpeed4.setDuration(newDuration); if (View.INVISIBLE != imgSpeed4.getVisibility()) { imgSpeed4.clearAnimation(); imgSpeed4.startAnimation(animSpeed4); } } newDuration = calcSpeedDuration(datagram.getSpeed5()); if (animSpeed5.getDuration() != newDuration) { animSpeed5.setDuration(newDuration); if (View.INVISIBLE != imgSpeed5.getVisibility()) { imgSpeed5.clearAnimation(); imgSpeed5.startAnimation(animSpeed5); } } newDuration = calcSpeedDuration(datagram.getSpeed6()); if (animSpeed6.getDuration() != newDuration) { animSpeed6.setDuration(newDuration); if (View.INVISIBLE != imgSpeed6.getVisibility()) { imgSpeed6.clearAnimation(); imgSpeed6.startAnimation(animSpeed6); } } // 风向改变 animDirection1 = new RotateAnimation(currentDirection1, datagram.getDirection1(), Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animDirection1.setDuration(500); animDirection1.setFillAfter(true); animDirection2 = new RotateAnimation(currentDirection2, datagram.getDirection2(), Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animDirection2.setDuration(500); animDirection2.setFillAfter(true); if (View.INVISIBLE != imgDirectionArrow1.getVisibility()) imgDirectionArrow1.startAnimation(animDirection1); if (View.INVISIBLE != imgDirectionArrow2.getVisibility()) imgDirectionArrow2.startAnimation(animDirection2); currentDirection1 = datagram.getDirection1(); currentDirection2 = datagram.getDirection2(); // 温度、湿度和气压 float newTemperature = (datagram.getTemperature() - ConstantsEwins.MIN_TEMPERATURE_VALUE) * ConstantsEwins.TEMPERATURE_STEP ConstantsEwins.MIN_TEMPERATURE_Y; float newHumidity = datagram.getHumidity() * ConstantsEwins.HUMIDITY_STEP ConstantsEwins.MIN_HUMIDITY_Y; float newPressure = (datagram.getPressure() - ConstantsEwins.MIN_PRESSURE_VALUE) * ConstantsEwins.PRESSURE_STEP; animTemperature = new ScaleAnimation(1.0f, 1.0f, currentTemperature, newTemperature, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.8f); animTemperature.setDuration(500); animTemperature.setFillAfter(true); animHumidity = new ScaleAnimation(1.0f, 1.0f, currentHumidity, newHumidity, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.8f); animHumidity.setDuration(500); animHumidity.setFillAfter(true); animPressure = new RotateAnimation(currentPressure, newPressure, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animPressure.setDuration(500); animPressure.setFillAfter(true); if (View.INVISIBLE != imgTemperaturePilar.getVisibility()) imgTemperaturePilar.startAnimation(animTemperature); if (View.INVISIBLE != imgHumidityPilar.getVisibility()) imgHumidityPilar.startAnimation(animHumidity); if (View.INVISIBLE != imgPressurePointer.getVisibility()) imgPressurePointer.startAnimation(animPressure); currentTemperature = newTemperature; currentHumidity = newHumidity; currentPressure = newPressure; } private long calcSpeedDuration(float speed) { int level; if (speed < 1.5f) level = 1; else if (speed > 1.6 && speed < 5.4) level = 2; else if (speed > 5.5 && speed < 7.9) level = 3; else if (speed > 8.0 && speed < 10.7) level = 4; else if (speed > 10.8 && speed < 13.8) level = 5; else if (speed > 13.9 && speed < 17.1) level = 6; else if (speed > 17.2 && speed < 20.7) level = 7; else if (speed > 20.8 && speed < 24.4) level = 8; else if (speed > 24.5 && speed < 28.4) level = 9; else if (speed > 28.5 && speed < 32.6) level = 10; else level = 11; long duration; duration = (11 - level) * ConstantsEwins.SPEED_DURATION_STEP ConstantsEwins.MIN_SPEED_DURATION; return duration; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { finish(); System.exit(0); } return true; } return super.onKeyDown(keyCode, event); } }