蓝牙的使用
工程结构图:
[img]
[/img]
MainActivity
package com.zzl.test;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button) findViewById(R.id.button1); btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(getApplication(),BTConnectActivity.class);startActivity(intent);finish();}}); }}
package com.zzl.test;/*************************************************************//* Project Shmimn * Mobile Health-care Device * Yuhua Chen * 2011-4-24 16:35:21 *//*************************************************************/import java.io.IOException;import java.util.UUID;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.content.Intent;import android.content.Context;import android.content.BroadcastReceiver;import android.content.IntentFilter;import android.widget.AdapterView;import android.widget.ListView;import android.widget.ArrayAdapter;import android.widget.Toast;import android.util.Log;import android.view.View;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.bluetooth.BluetoothSocket;public class BTConnectActivity extends Activity {// private static final String TAG = "BTConnectActivity";/** Called when the activity is first created. */public static final int REQUEST_ENABLE_BT = 8807;public BroadcastReceiver mBTReceiver;public static BluetoothSocket mBTSocket;public BluetoothAdapter mBTAdapter;public BluetoothDevice mBTDevice;private ArrayAdapter<String> adtDvcs;private List<String> lstDvcsStr = new ArrayList<String>();private ListView lvDevicesList;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.btconnect);// 初始化 BluetoothAdaptermBTAdapter = BluetoothAdapter.getDefaultAdapter(); // cif (mBTAdapter == null) {Toast.makeText(BTConnectActivity.this, "没有支持蓝牙的设备! ",Toast.LENGTH_SHORT).show();this.finish();}if (!mBTAdapter.isEnabled()) {// Open a new dialog to ask user whether wanna open BTToast.makeText(BTConnectActivity.this, "请打开手机蓝牙后再重试! ",Toast.LENGTH_SHORT).show();this.finish();Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(enabler, REQUEST_ENABLE_BT);}// 开启 BroadCast ReceivermBTReceiver = new BroadcastReceiver() {public void onReceive(Context context, Intent intent) {String act = intent.getAction();// To see whether the action is that already found devicesif (act.equals(BluetoothDevice.ACTION_FOUND)) {// 如果发现一个设备,得到设备的对象BluetoothDevice tmpDvc = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);// Put the name & address into a stringString tmpDvcStr = tmpDvc.getName() + "|"+ tmpDvc.getAddress();if (lstDvcsStr.indexOf(tmpDvcStr) == -1) {// Avoid duplicate add deviceslstDvcsStr.add(tmpDvcStr);adtDvcs.notifyDataSetChanged();Toast.makeText(BTConnectActivity.this, "发现一个新设备",Toast.LENGTH_SHORT).show();}}if (act.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {Toast.makeText(BTConnectActivity.this, "搜索完成!",Toast.LENGTH_SHORT).show();}if (act.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {Toast.makeText(BTConnectActivity.this, "开始搜索设备",Toast.LENGTH_SHORT).show();}}};// 注册 broadcastReceiverIntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);registerReceiver(mBTReceiver, filter);filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);registerReceiver(mBTReceiver, filter);filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);registerReceiver(mBTReceiver, filter);lvDevicesList = (ListView) findViewById(R.id.lvDevicesList);adtDvcs = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, lstDvcsStr);lvDevicesList.setAdapter(adtDvcs);if (mBTAdapter.isDiscovering()) {Toast.makeText(BTConnectActivity.this, "正在搜索......",Toast.LENGTH_SHORT).show();} else {lstDvcsStr.clear();adtDvcs.notifyDataSetChanged();mBTDevice = null;mBTAdapter.startDiscovery();}// 在设备列表中创建单击事件lvDevicesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {if (mBTAdapter == null)Toast.makeText(BTConnectActivity.this, "没有搜索到蓝牙设备",Toast.LENGTH_SHORT).show();else {// 停止搜索mBTAdapter.cancelDiscovery();// 得到设备的地址String str = lstDvcsStr.get(arg2);String[] dvcValues = str.split("\\|");String dvcAddr = dvcValues[1];UUID dvcUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");mBTDevice = mBTAdapter.getRemoteDevice(dvcAddr);// 连接设备try {// 根据UUID创建并返回一个BluetoothSocketmBTSocket = mBTDevice.createRfcommSocketToServiceRecord(dvcUUID);mBTSocket.connect();Intent intent = new Intent(getApplicationContext(),WriteActivity.class);startActivity(intent);} catch (IOException e) {e.printStackTrace();}}}});}public void onActivityResult(int RequestCode, int ResultCode, Intent data) {Log.i("BTConnectActivity", "RequestCode is " + RequestCode+ ", ResultCode is " + ResultCode);switch (RequestCode) {case REQUEST_ENABLE_BT:if (ResultCode == RESULT_OK) {Toast.makeText(this.getApplicationContext(), "蓝牙已连接!",Toast.LENGTH_SHORT).show();} else if (ResultCode == RESULT_CANCELED) {Toast.makeText(this.getApplicationContext(), "蓝牙连接被取消!",Toast.LENGTH_SHORT).show();}break;}}@Overrideprotected void onDestroy() {try {mBTSocket.close();} catch (IOException e) {e.printStackTrace();}this.unregisterReceiver(mBTReceiver);super.onDestroy();}}
package com.zzl.test;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;public class WriteActivity extends Activity { private TextView tv;private BTReadThread mReadThread = new BTReadThread(50);private boolean enRead = false; private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 0:tv.setText(msg.obj.toString());break;}}}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.write); tv = (TextView) findViewById(R.id.tv); btint(); } /** * 开启读取蓝牙数据的线程 */private void btint() {try {if (BTConnectActivity.mBTSocket.getInputStream() != null) {enRead = true;mReadThread.start();}} catch (Exception e) {e.printStackTrace();}}/*** * 蓝牙操作 */class BTReadThread extends Thread {private int wait = 50;// Time to waitpublic BTReadThread(int wait) {this.wait = wait;}public void stopThread(){enRead = false;}public void run() {while (enRead) {try {if (BTConnectActivity.mBTSocket.getInputStream() != null) {byte[] tmp = new byte[1024];int len = BTConnectActivity.mBTSocket.getInputStream().read(tmp, 0, 1024); // 卡if (len > 0) {String res = "";for (int i = 0; i < tmp.length; i++) {String hex = Integer.toHexString(tmp[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}res += hex.toUpperCase();}String strDES = res.substring(0, 16);Message message = handler.obtainMessage();message.what = 0;message.obj = strDES;handler.sendMessage(message);}}Thread.sleep(wait);} catch (Exception e) {e.printStackTrace();}}}}}