蓝牙连接电子称以及解析电子称返回的数据


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 net.intelink.express.SZYDPDA.R;
import net.intelink.express.adapter.CommonAdapter;
import net.intelink.express.adapter.ViewHolder;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
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.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BlueToothActivity extends BaseActivity {

	BluetoothAdapter adapter;
	private TextView tv_count;
	InputStream inputStream = null;
	private boolean mIsRunning = false;

	private List devices;
	private List deviceList;
	private final String lockName = "BOLUTEK";

	private ListView list;
	private ProgressDialog dialog = null;
	private ProgressDialog isingDialog=null;

	private boolean isConnected = false;
	
	private CommonAdapter commonAdapter;
	private StringBuffer sBuffer=new StringBuffer();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_blue_tooth);

		list = (ListView) findViewById(R.id.list);
		tv_count = (TextView) findViewById(R.id.tv_count);
		devices = new ArrayList();
		deviceList = new ArrayList();

		search();
	}

	private void search() {
		adapter = BluetoothAdapter.getDefaultAdapter();
		if (!adapter.isEnabled()) {
			adapter.enable();
		}
		// Intent enable = new
		// Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		// enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);
		// startActivity(enable);

		// IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		// registerReceiver(receiver, filter);
		
		
		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();
		dialog = ProgressDialog.show(this, "", "正在搜索");
		dialog.setCancelable(false);
		dialog.setOnKeyListener(onKeyListener);

		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView parent, View view, int position, long id) {
				BluetoothDevice device = deviceList.get(position);
				connect(device);
			}
		});
		
		commonAdapter=new CommonAdapter(this, devices, R.layout.activity_blue_tooth_item) {

			@Override
			public void convert(ViewHolder holder, String item) {
				holder.setText(R.id.tv_address, item);
			}
		};
		list.setAdapter(commonAdapter);
		
		bluetoothSocket=mApplication.getSocket();
		if(bluetoothSocket!=null){
			mysocket();
		}
	}
	
	private void mysocket() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					if (bluetoothSocket != null) {
						inputStream = bluetoothSocket.getInputStream();
						mIsRunning = true;
					}
					while (mIsRunning) {
						byte[] buffer = new byte[16];
						if (inputStream != null && inputStream.read(buffer) > 0 && mIsRunning) {
							Message msg = mHandler.obtainMessage();
							msg.what = 1;
							msg.obj = new String(buffer);
							mHandler.sendMessage(msg);
							Log.i("OIJOI", new String(buffer));
							Arrays.fill(buffer, (byte) 0);
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// 搜索设备时,取得设备的MAC地址
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (isLock(device)) {
					commonAdapter.add(device.getName());
					deviceList.add(device);
				}
			}
			showDevices();
		}
	};

	private void showDevices() {
		if(devices!=null && devices.size()>0){
			commonAdapter.notifyDataSetChanged();
		}
	}

	private void connect(final BluetoothDevice device) {

		isingDialog=ProgressDialog.show(this, "", "连接中");
		isingDialog.setCancelable(false);
		isingDialog.setOnKeyListener(onKeyListener);
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
					bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								if (bluetoothSocket != null) {
									if (bluetoothSocket.isConnected()) {
										Message msg = mHandler.obtainMessage();
										msg.what = 3;
										mHandler.sendMessage(msg);
									} else {
										bluetoothSocket.connect();
										isConnected = true;
										mApplication.setSocket(bluetoothSocket);//保存

										if (bluetoothSocket != null) {
											inputStream = bluetoothSocket.getInputStream();
											mIsRunning = true;
										}
										while (mIsRunning) {
											byte[] buffer = new byte[16];
											if (inputStream != null && inputStream.read(buffer) > 0 && mIsRunning) {
												Message msg = mHandler.obtainMessage();
												msg.what = 1;
												msg.obj = new String(buffer);
												mHandler.sendMessage(msg);
												Log.i("OIJOI", new String(buffer));
												Arrays.fill(buffer, (byte) 0);
											}
										}
									}
								}

							} catch (Exception e) {
								e.printStackTrace();
								isConnected = false;

								Message msg = mHandler.obtainMessage();
								msg.what = 2;
								mHandler.sendMessage(msg);
							}

						}
					}).start();

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	private boolean isLock(BluetoothDevice device) {
		// boolean isLockName=(device.getName()).equals(lockName);
		boolean isSingleDevice = devices.indexOf(device.getName()) == -1;
		// return isLockName && isSingleDevice;
		return isSingleDevice;
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if(isingDialog!=null){
				isingDialog.dismiss();
				isingDialog=null;
			}
			switch (msg.what) {
			case 1:
				String result = String.valueOf(msg.obj).trim().replace("\n", "");
				if (result != null && !"".equals(result)) {
					sBuffer.append(result);
					
					String myResult=sBuffer.toString();
					System.out.println(myResult);
					if(myResult.contains("wn") && myResult.contains("kg")){
						if (myResult.indexOf("wn") < myResult.lastIndexOf("kg")) {
							if(myResult.contains("kgwn")){
								tv_count.setText(myResult.substring(0,myResult.indexOf("kgwn")));
								Log.i("www", myResult.substring(0,myResult.indexOf("kgwn")));
							}else {
								tv_count.setText(myResult.substring(myResult.indexOf("wn") + 2, myResult.lastIndexOf("kg")));
								Log.i("www",myResult.substring(myResult.indexOf("wn") + 2, myResult.lastIndexOf("kg")));
							}
						}
					}
					sBuffer.delete(0,  myResult.lastIndexOf("kg")+2);
					Log.i("qqq", new String(sBuffer.toString()));
					
				}
				break;
			case 2:
				if (isConnected == false) {
					Toast.makeText(BlueToothActivity.this, "蓝牙连接失败.", Toast.LENGTH_SHORT).show();
				}
				break;
			case 3:
				Toast.makeText(BlueToothActivity.this, "蓝牙已连接.", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	};

	private OnKeyListener onKeyListener = new OnKeyListener() {
		@Override
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
				if (dialog != null) {
					dialog.dismiss();
				}
				if(isingDialog!=null){
					isingDialog.dismiss();
				}
				if (adapter.isDiscovering()) {
					adapter.cancelDiscovery();
				}
			}
			return false;
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case F5:
			if(!adapter.isDiscovering()){
				adapter.startDiscovery();
				dialog = ProgressDialog.show(this, "", "正在搜索");
				dialog.setCancelable(false);
				dialog.setOnKeyListener(onKeyListener);
			}
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
}

你可能感兴趣的:(Android)