Android链接蓝牙电子称
蓝牙一直是我内心屏蔽的一个模块哈哈哈哈!然而今天我不得不正视它了,我百度了看了好多因为需要设备匹配所以设备不在没办法测试,几天之后设备到了。因为没有接触过,看到返回的打印出来的菱形方块就以为是错了。于是一直在找解决的办法,然而也看不出有什么错误。结果其实是正确的┭┮﹏┭┮,下面贴一下我的代码:
package com.schw.ui.recyle;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import com.schw.R;
import com.schw.ui.base.activity.BaseActivity;
import com.schw.util.SharePreferUtil;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainBlothActivity extends BaseActivity {
private ListView blothList;
private List<BluetoothDevice> devices=new ArrayList<BluetoothDevice>();
private BluetoothAdapter adapter;
private DeviceListAdapter dListAdapter;
private BluetoothSocket bSocket;
private boolean mIsRuning=false;
private boolean isConnected=false;
private InputStream inputStream;
private StringBuffer sBuffer=new StringBuffer();
public static final UUID uuid=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
// TODO Auto-generated method stub
switch (msg.what) {
case 1:
Log.i("成功", "蓝牙已链接");
mIsRuning=false;
hindProgress();
String string = (String) msg.obj;
Log.i("Handler",string);
Intent intent=new Intent();
intent.putExtra("dataW", string);
setResult(RESULT_OK, intent);
finish();
break;
case 2:
if(isConnected==false){
Toast.makeText(getApplicationContext(), "蓝牙链接失败!",Toast.LENGTH_SHORT).show();
hindProgress();
// search();
}
break;
case 3:
Toast.makeText(getApplicationContext(), "蓝牙已链接!",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return false;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main_bloth);
blothList = (ListView) findViewById(R.id.blothList);
mActionbar.setActionBarTitle("蓝牙列表");
search();
}
private void search() {
// TODO Auto-generated method stub
adapter = BluetoothAdapter.getDefaultAdapter();
if(!adapter.isEnabled()){
adapter.enable();
}
IntentFilter intentFilter =new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver,intentFilter);
adapter.startDiscovery();
blothList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
initProgress("加载中……");
BluetoothDevice device = devices.get(position);
SharePreferUtil.saveDeviceAddress(getApplicationContext(), device.getAddress());
// SharePreferUtil.saveDeviceAddress(getApplicationContext(), device.getName());
connect(device);
}
});
dListAdapter=new DeviceListAdapter();
blothList.setAdapter(dListAdapter);
if(bSocket!=null){
myScket();
}
}
private void myScket() {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if(bSocket!=null){
try {
inputStream = bSocket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mIsRuning=true;
}
while(mIsRuning){
byte[] buffer=new byte[16];
try {
if(inputStream!=null&&inputStream.read(buffer)>0&&mIsRuning){
String string = new String(buffer);
Log.i("MessageFill", string);
Log.i("LastString", string.substring(0, 6));
// Message msg=new Message();
// msg.what=1;
// msg.obj=string;
// handler.sendMessage(msg);
// break;
Log.i("TAG", string.substring(0,1));
if(!string.equals("")&&string.substring(0,1).equals("=")){
Intent intent=new Intent();
intent.putExtra("dataW", string);
setResult(RESULT_OK, intent);
finish();
break;
}else{
Log.i("MessageFillelse==", string);
// Intent intent=new Intent();
// intent.putExtra("dataW", "false???");
// setResult(RESULT_OK, intent);
// finish();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
private BroadcastReceiver receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice parcelableExtra = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(isLock(parcelableExtra)){
dListAdapter.addDevice(parcelableExtra);
devices.add(parcelableExtra);
}
}
showDevices();
}
};
private void showDevices() {
// TODO Auto-generated method stub
if(devices!=null&&devices.size()>0){
dListAdapter.notifyDataSetChanged();
}
}
private void connect(final BluetoothDevice device) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
bSocket=device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(new Runnable() {
@Override
public void run() {
// // TODO Auto-generated method stub
try {
if(bSocket!=null){
if(bSocket.isConnected()){
Message msg=new Message();
msg.what=3;
handler.sendMessage(msg);
}else{
try {
bSocket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isConnected=true;
if(bSocket!=null){
try {
inputStream = bSocket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mIsRuning=true;
}
while(mIsRuning){
Log.i("RUNG????????", mIsRuning+"");
byte[] buffer=new byte[16];
try {
if(inputStream!=null&&inputStream.read(buffer)>0&&mIsRuning){
String string = new String(buffer);
Log.i("MessageFill", string);
Log.i("LastString", string.substring(0, 6));
// Message msg=new Message();
// msg.what=1;
// msg.obj=string;
// mHandler.sendMessage(msg);
// break;
Log.i("TAG", string.substring(0,1));
Log.i("TAG8", string.substring(8, 9));
if(!string.equals("")&&string.substring(0,1).equals("=")&&(string.substring(8, 9)).equals("=")){
// Intent intent=new Intent();
// intent.putExtra("dataW", string);
// setResult(RESULT_OK, intent);
// finish();
// String d=string.substring(2,3);
// String c=string.substring(3,4);
// String b=string.substring(4,5);
// String a=string.substring(5,6);
// Log.i("abcd",a+b+c+d);
// String wb=a+b+c+d;
// et_weight.setText(wb);
Message msg=new Message();
msg.what=1;
msg.obj=string;
handler.sendMessage(msg);
hindProgress();
// break;
}else{
Log.i("MessageFillelse==", string);
hindProgress();
// Intent intent=new Intent();
// intent.putExtra("dataW", "false???");
// setResult(RESULT_OK, intent);
// finish();
// isConnect=false;
}
}
// }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
isConnected=false;
Message msg=new Message();
msg.what=2;
handler.sendMessage(msg);
}
}
}).start();
}
}).start();
}
private boolean isLock(BluetoothDevice device){
boolean isSingleDevice = devices.indexOf(device.getName())==-1;
return isSingleDevice;
}
// Handler mHandler=new Handler(){
// @SuppressWarnings("unused")
// public void handlerMessage(Message msg){
// switch(msg.what){
// case 1:
// String valueOf = (String) msg.obj;
// Log.i("称重=====",valueOf);
// break;
// case 3:
// Log.i("成功", "蓝牙已链接");
// break;
// }
// }
// };
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
try {
bSocket.close();
adapter.cancelDiscovery();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
class DeviceListAdapter extends BaseAdapter {
private List<BluetoothDevice> mBleArray;
private ViewHolder viewHolder;
public DeviceListAdapter() {
mBleArray = new ArrayList<BluetoothDevice>();
}
public void addDevice(BluetoothDevice device) {
if (!mBleArray.contains(device)) {
mBleArray.add(device);
}
}
public void clear() {
mBleArray.clear();
}
@Override
public int getCount() {
return mBleArray.size();
}
@Override
public BluetoothDevice getItem(int position) {
return mBleArray.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(MainBlothActivity.this).inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.tv_devName = (TextView) convertView.findViewById(R.id.device_name);
viewHolder.tv_devAddress = (TextView) convertView.findViewById(R.id.device_address);
convertView.setTag(viewHolder);
} else {
convertView.getTag();
}
// add-Parameters
BluetoothDevice device = mBleArray.get(position);
String devName = device.getName();
if (devName != null && devName.length() > 0) {
viewHolder.tv_devName.setText(devName);
} else {
viewHolder.tv_devName.setText("unknow-device");
}
viewHolder.tv_devAddress.setText(device.getAddress());
return convertView;
}
}
class ViewHolder {
TextView tv_devName, tv_devAddress;
}
@Override
protected void doSuccess(Message msg) {
// TODO Auto-generated method stub
}
@Override
protected void doError(Message msg) {
// TODO Auto-generated method stub
}
@Override
protected int getContentLayout() {
// TODO Auto-generated method stub
return R.layout.activity_main_bloth;
}
}
但是,这里是又一个问题的,就我获取来的数据是倒过来的。而且是随机的不规则的
所以我硬是生生的给正过来了。我知道肯定又简单的方法,但是我没有找到。也希望大家也能帮我看看。
Android链接蓝牙电子称的更多相关文章
- android 链接蓝牙不稳定的解决建议
My workaround I scan BLE for a short period of time 3-4 seconds then I turn scan OFF for 3-4 seconds ...
- 锅巴视频工作室 ----------------android端蓝牙测试demo--app
android端蓝牙测试demo--app 这个是为一个客户做蓝牙项目时的一个测试demo,用来测试蓝牙单片机的收发情况,代码中没有做一些兼容性测试,请理解 锅巴视频工作室,专注于android视频相 ...
- Android 串口蓝牙通信开发Java版本
Android串口BLE蓝牙通信Java版 0. 导语 Qt on Android 蓝牙通信开发 我们都知道,在物联网中,BLE蓝牙是通信设备的关键设备.在传统的物联网应用中,无线WIFI.蓝牙和Zi ...
- ubuntu16.04连接android手机蓝牙共享网络热点
最近的想要用android手机蓝牙共享wifi网络给ubuntu16.04系统用,查了好多资料,发现网上很少有有用的.自己实践后分享如下. 第一步:手机与电脑配对: 该步骤比较简单,网 ...
- Android BLE 蓝牙编程(一)
最近在研究这个,等我有时间来写吧! 终于在端午节给自己放个假,现在就来说说关于android蓝牙ble的 最近的学习成果吧!! 需要材料(写个简单教程吧--关于小米手环的哦!嘿嘿) Android 手 ...
- 【转】Android bluetooth介绍(二): android blueZ蓝牙代码架构及其uart 到rfcomm流程
原文网址:http://blog.sina.com.cn/s/blog_602c72c50102uzoj.html 关键词:蓝牙blueZ UART HCI_UART H4 HCI L2CAP ...
- 【转】Android低功耗蓝牙应用开发获取的服务UUID
原文网址:http://blog.csdn.net/zhangjs0322/article/details/39048939 Android低功耗蓝牙应用程序开始时获取到的蓝牙血压计所有服务的UUID ...
- Android ble 蓝牙4.0 总结
本文介绍Android ble 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用,如果手机系统版本API level < 18,也是用不了蓝牙4.0的哦 ...
- 【源代码】基于Android和蓝牙的单片机温度採集系统
如需转载请标明出处:http://blog.csdn.net/itas109 QQ技术交流群:129518033 STC89C52单片机通过HC-06蓝牙模块与Android手机通信实例- 基于And ...
随机推荐
- Go语言指针
指针简介 (Pointer)是编程语言中的一个对象,利用地址,它的值直接指向(points to)存在电脑存储器中另一个地方的值.由于通过地址能找到所需的变量单元,可以说,地址指向该变量单元.因此,将 ...
- C#静态和实例
静态 实例 关键字static修饰类或方法 不能使用static修饰类或方法 修饰后类直接调用 需要先实例化对象,用对象调用 静态只会执行调用一次,并且在程序退出之前会一直保持状态,占领内存 实例化一 ...
- dotnet core webapi +vue 搭建前后端完全分离web架构(一)
架构 服务端采用 dotnet core webapi 前端采用: Vue + router +elementUI+axios 问题 使用前后端完全分离的架构,首先遇到的问题肯定是跨域访问.前后端可 ...
- mono for android读书笔记之真机调试(转)
调试环境: 1.软件:monodevelop v3.0.3.5 2.硬件:华为C8650s手机一部,数据线一根,thinkpad e420笔记本电脑一台 调试的应用程序有一个Activity,Acti ...
- 通过数据库绑定的dropdownlist,如何让其第一条默认显示"--请选择--"
第一种方法 DropDownList1.Items.Insert(0,"请选择XXX"); 第二种方法 在第一个位置插入一个项就可以 DropDownList1.Items.Ins ...
- 第十篇---javascript函数this关键字
<script type="text/javascript" charset="utf-8"> //this:this对象是指运行时期基于执行环境所 ...
- Struts dispatchAction
在Struts中定义动态Action,不用定义多个Action,可以实现一个action,多个跳转. 在定义时,继承DispatchAction,并定义parameter的名字 在jsp页面选择act ...
- 设计模式--策略模式(strategy)
1.策略模式(strategy ['strætədʒi]) 我的理解是:方案候选模式 (反正关键就是有很多的候选,哈哈) 看了很多例子,都是在说鸭子的,那个例子很好,在这里可以看 他们生产鸭子,我们就 ...
- NetXray
NetXRay是由Cinco Networks公司开发的一个用于高级分组检错的软件,功能很强大.IP地址查询工具. 硬件要求 对硬件要求低,可运行常用的windows平台. 主要功能 1.监视网络状态 ...
- [CPP] Object Based Class
前言 几年前接触到一款很好玩的RPG游戏,叫作CPP.最近想着怀念一下,又不想干巴巴地去玩.于是乎,我打算写几篇攻略,主要是记录一下游戏中一些奇妙的点.游戏的第一章是面向对象程序设计,其中又分为基于对 ...