蓝牙一直是我内心屏蔽的一个模块哈哈哈哈!然而今天我不得不正视它了,我百度了看了好多因为需要设备匹配所以设备不在没办法测试,几天之后设备到了。因为没有接触过,看到返回的打印出来的菱形方块就以为是错了。于是一直在找解决的办法,然而也看不出有什么错误。结果其实是正确的┭┮﹏┭┮,下面贴一下我的代码:
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
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
private ViewHolder viewHolder;
public DeviceListAdapter() {
mBleArray = new ArrayList
}
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;
}
}
但是,这里是又一个问题的,就我获取来的数据是倒过来的。而且是随机的不规则的所以我硬是生生的给正过来了。我知道肯定又简单的方法,但是我没有找到。也希望大家也能帮我看看。