package com.creative.item03;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;import android.app.Activity;
import android.app.ProgressDialog;
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.view.KeyEvent;public class BluetoothDiscovery extends Activity { public static final UUID MyUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();// 获取蓝牙设备
private Set<BluetoothDevice> devices = null;
private BluetoothDevice device;
private BluetoothDevice btDev;
private static BluetoothSocket mSocket;
private ProgressDialog bluetoothPro;
private boolean bluetoothstause = true;
private Intent recalled;
private connectbluetooth connectdevice = null;
private volatile boolean _discoveryFinished;
private discover myDiscovery = new discover();
private ConnectThread connectThread = null;
private Timer timer = new Timer();
private static final int TIMEROUT = 10; public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.discovery);
// 创建一个进度条
bluetoothPro = new ProgressDialog(this); /*
 * 调用bluetoothSet函数 获取当前已经配对的蓝牙列表 并且查找到对应设备 返回0 表示没有找到设备 开始搜索
 * 返回非0表示已找到设备 开始连接
 */
if (bluetoothSet() == 0) {
Discovery();
} else {
bluetoothPro.setMessage("Connecting...");
bluetoothPro.show();
connectThread = new ConnectThread(device);
connectThread.start();
}
} // 搜索设备开始的函数
public void Discovery() {
/* 注册接收器 */
IntentFilter discoveryFilter = new IntentFilter(
BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(_discoveryReceiver, discoveryFilter); IntentFilter foundFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(_foundReceiver, foundFilter); // 设定30秒超时
timer.schedule(timertask, TIMEROUT * 1000); // 再次去确定蓝牙设备状态
if (!adapter.isEnabled()) {
adapter.enable();
}
// 设置进度条显示的提示信息
bluetoothPro.setMessage("Discovery...");
bluetoothPro.show();
// 启动线程开始搜索设备
myDiscovery.start();
} TimerTask timertask = new TimerTask() { @Override
public void run() {
// TODO Auto-generated method stub
if (adapter.isDiscovering()) {
adapter.cancelDiscovery();
bluetoothPro.dismiss();
bluetoothstause = true;
recalled = BluetoothDiscovery.this.getIntent();
recalled.putExtra("nofind", bluetoothstause);
BluetoothDiscovery.this.setResult(R.layout.activity_main,
recalled);
finish();
}
}
}; // 在线程中搜索设备
public class discover extends Thread { @Override
public void run() {
// TODO Auto-generated method stub
super.run(); adapter.startDiscovery();
for (;;) { if (_discoveryFinished) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
} // 完成配对 并且发送消息给主线程 开始连接蓝牙
public class connectbluetooth extends Thread { BluetoothDevice mDevice; public connectbluetooth(BluetoothDevice newdevice) {
mDevice = newdevice;
btDev = newdevice;
} @Override
public void run() {
// TODO Auto-generated method stub
super.run();
// 更加设备地址 返回一个远程蓝牙设备
// btDev = adapter.getRemoteDevice(mDevice.getAddress());
System.out.println("btDev==" + btDev);
try {
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
Method createBondMethod = BluetoothDevice.class
.getMethod("createBond");
createBondMethod.invoke(btDev);
}
// System.out.println("准备连接");
mHandler.sendEmptyMessage(0x01);
} catch (Exception e) {
e.printStackTrace();
// System.out.println("连接异常" + e.getMessage());
Finish(true);
}
}
} Handler mHandler = new Handler() { @Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case 0x01: {
adapter.cancelDiscovery();
if(bluetoothPro.isShowing()){
bluetoothPro.dismiss();
}
bluetoothPro.setMessage("Connecting...");
bluetoothPro.show();
connectThread = new ConnectThread(btDev);
connectThread.start();
}
break;
default:
break;
}
} }; public int bluetoothSet() {
devices = adapter.getBondedDevices();
int cnt = 0;
if (devices.size() > 0) {
for (Iterator<BluetoothDevice> it = devices.iterator(); it
.hasNext();) {
device = (BluetoothDevice) it.next();
if (device.getName().equals("PC-60NW")) {
cnt++;
break;
}
}
}
return cnt;
} // 连接蓝牙设备线程
private class ConnectThread extends Thread { private BluetoothDevice mDevice; public ConnectThread(BluetoothDevice fDevice) {
BluetoothSocket temp = null;
mDevice = fDevice;
try {
temp = mDevice.createRfcommSocketToServiceRecord(MyUUID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println("temp= " + temp.toString());
mSocket = temp;
} @Override
public void run() {
// TODO Auto-generated method stub
super.run();
// System.out.println("开始连接====" + mDevice.getBondState());
while (true) {
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
try {
// System.out.println("开始连接====" + mDevice.getBondState());
// System.out.println(mDevice.getAddress() + " "
// + mSocket.toString());
mSocket.connect();
MainActivity.setFis(mSocket.getInputStream());
MainActivity.setFos(mSocket.getOutputStream());
// System.out.println("连接成功返回");
Finish(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
mSocket.close();
System.out.println("连接失败 " + e.getMessage());
Finish(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
}
break;
} else {
try {
sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} } @SuppressWarnings("unused")
public void cancel() {
try {
mSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // 搜索设备的广播监听器 如果搜索到设备 将回调该方法
private BroadcastReceiver _foundReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
/* 从intent中取得搜索结果数据 */
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // 发现设备时 先改变进度条样式 在启动连接设备线程 同时取消蓝牙设备的搜索功能
if (device.getName().equals("PC-60NW")) {
adapter.cancelDiscovery();
connectdevice = new connectbluetooth(device);
connectdevice.start();
// System.out.println("接收到设备--------->" + device.getName());
}
}
};
private BroadcastReceiver _discoveryReceiver = new BroadcastReceiver() { @Override
public void onReceive(Context context, Intent intent) {
/* 卸载注册的接收器 */
unregisterReceiver(_foundReceiver);
unregisterReceiver(this);
_discoveryFinished = true;
}
}; public void Finish(boolean stause) {
if (bluetoothPro.isShowing()) {
bluetoothPro.dismiss();
}
bluetoothstause = stause;
recalled = this.getIntent();
recalled.putExtra("nofind", bluetoothstause);
this.setResult(R.layout.activity_main, recalled);
// System.out.println("Finish");
finish();
} public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
adapter.cancelDiscovery();
Finish(true);
}
return super.onKeyDown(keyCode, event);
} public static void Bluetoothquit(){
if(mSocket != null){
try {
mSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
程序启动都是先查找已经配对的设备 看有没有目标设备 如果有就连接 没有就开始搜索 第一次运行  搜索能搜索到 但是连接不上 这个时候看系统蓝牙里面 搜索到的这个设备已经配对上了 然后再运行程序 这个时候直接开始连接 一般都能成功  
还有就是连接上之后  老是读取异常 蓝牙设备一直在发送数据 程序有时候收着收着就报异常了 感觉很不稳定 
各位高人 给小弟指点指点吧