louxindong

import java.io.IOException;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import android.annotation.SuppressLint;
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.util.Log;
import android.widget.ArrayAdapter;

@SuppressLint("NewApi")
public class BluetoothUtil {
ArrayAdapter<String> adtDevices;
List<String> lstDevices = new ArrayList<String>();
//static BluetoothUtil bluetoothUtil;// 静态单例
BluetoothAdapter btAdapt = null; //蓝牙适配器
BluetoothDevice device = null; //蓝牙设备驱动
BluetoothSocket btSocket; //蓝牙通信
String btAddress; //蓝牙MAC地址
BtInputThread btInputThread; //输入流
OutputStream out; //输出流

/**
* 构造函数
* @param context 环境上下文
*/
public BluetoothUtil(Context context){
this.init(context);
}

//单例模式
/*public static BluetoothUtil getInstance(Context context) {
if(null == bluetoothUtil){
bluetoothUtil = new BluetoothUtil(context);
}
return bluetoothUtil;
}*/

/**
* 初始化本机蓝牙功能
* @param context
*/
private void init(Context context){
if(null == btAdapt){
btAdapt = BluetoothAdapter.getDefaultAdapter(); //获取蓝牙适配器当前对象
String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.addAction(ACTION_PAIRING_REQUEST);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
context.registerReceiver(searchDevices, intent);
}
}

/**
* 获取蓝牙列表
*
*/
private BroadcastReceiver searchDevices = new BroadcastReceiver() {
@SuppressLint("NewApi")
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
Object[] lstName = b.keySet().toArray();

// 显示所有收到的消息及其细节
for (int i = 0; i < lstName.length; i++) {
String keyName = lstName[i].toString();
Log.e(keyName, String.valueOf(b.get(keyName))+"======");
}
//蓝牙状态
if(intent.getAction().equals("android.bluetooth.adapter.action.STATE_CHANGED")){
switch(BluetoothAdapter.getDefaultAdapter().getState()){
case BluetoothAdapter.STATE_ON:
ResponseUtil.receive(new ResultObj(1,"蓝牙开启成功"));
Log.d("BluetoothAdapter", "蓝牙已开启");
break;
case BluetoothAdapter.STATE_OFF:
Log.d("BluetoothAdapter", "蓝牙已关闭");
case BluetoothAdapter.STATE_TURNING_ON:
//Log.d("BluetoothAdapter", "蓝牙运行中");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
//Log.d("BluetoothAdapter", "蓝牙运行关闭");
default:
break;
}
}
// 搜索设备时,取得设备的MAC地址
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//得到设备实例,异步通知
//ResponseUtil.receive(device);
}else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
switch (device.getBondState()) {
case BluetoothDevice.BOND_BONDING:
Log.d("", "正在配对");
ResponseUtil.receive(new ResultObj(1,"正在配对"));
break;
case BluetoothDevice.BOND_BONDED:
//异步通知刘挺
if(device.getBondState() == BluetoothDevice.BOND_BONDED) {
ResponseUtil.receive(new ResultObj(1,"完成配对"));
createConnect(device);//创建蓝牙通信
}
break;
case BluetoothDevice.BOND_NONE:
if (null!=btSocket && btSocket.isConnected()) {
try {
btInputThread.interrupt();
out.close();
btSocket.close();
} catch (IOException e) {

e.printStackTrace();
}
}
ResponseUtil.receive(new ResultObj(1,"取消配对"));
break;
default:
break;
}
}
//回调执行蓝牙配对,设置PIN码
if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST"))
{
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
btDevice.setPin("919290".getBytes());
btDevice.createBond();
}
}
};

/**
* 连接蓝牙
* @param mac 蓝牙mac地址
*/
public ResultObj connectBluetooch(String macAddress){
//当连接的mac地址与上次不同时,关闭所有资源
if(null != btAddress && !btAddress.equals(macAddress)){
cancelConnect();
} else {
//蓝牙通信已建立不用重复建立
if (null!=btSocket && btSocket.isConnected()) {
ResponseUtil.receive(new ResultObj(1001,"蓝牙通信建立连接成功"), 500);
return new ResultObj(1, "调用 connect 方法成功");
}
}
if(btAdapt.isDiscovering()) { // 取消蓝牙搜索
btAdapt.cancelDiscovery();
}
if (!btAdapt.isEnabled()) { // 开启蓝牙
btAdapt.enable();
}
//检查蓝牙地址是否有效
if (!BluetoothAdapter.checkBluetoothAddress(macAddress)) {
return new ResultObj(1000, "蓝牙mac地址无效");
}
//蓝牙配对
this.device = pair(macAddress, "919290");
if(device.getBondState() == BluetoothDevice.BOND_BONDED) {
createConnect(device);
}
return new ResultObj(1, "调用 connect 方法成功");
}

/**
* 蓝牙配对
* @param macAddress
* @param password
* @return
*/
public BluetoothDevice pair(String macAddress, String password) {
if (btAdapt.isDiscovering()) { // 取消蓝牙搜索
btAdapt.cancelDiscovery();
}
if (!btAdapt.isEnabled()) { // 开启蓝牙
btAdapt.enable();
}
BluetoothDevice device = btAdapt.getRemoteDevice(macAddress); //根据蓝牙设备的MAC地址,获取蓝牙设备驱动
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
device.createBond();
}
return device;
}

/**
* 搜索蓝牙设备
*
*/
private void search(){

}

/**
* 创建设备蓝牙通信连接
* @param btDev 蓝牙设备实例
*/
private void createConnect(BluetoothDevice btDev){
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
try {
btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
btSocket.connect();
out = btSocket.getOutputStream();
if(null == btInputThread || !btInputThread.isAlive()){
btInputThread = new BtInputThread(btSocket);
btInputThread.start();
}
ResponseUtil.receive(new ResultObj(1001,"蓝牙通信建立连接成功"));
} catch (IOException e) {
ResponseUtil.receive(new ResultObj(-1,"与蓝牙设备创建连接失败"));
}
}
/**
* 取消连接
* @return
*/
public ResultObj cancelConnect(){
try {
if(null != out){
out.close();
}
if(null != btInputThread){
btInputThread.interrupt();
}
if(null != btSocket){
btSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
return new ResultObj(1,"取消连接异常");
}
return new ResultObj(1,"取消连接成功");
}

/**
* 发送请求到设备
* @param bytes
* @throws IOException
*/
public ResultObj send(byte[] bytes){
if(null == btSocket){
return new ResultObj(-1,"Socket未创建");
}
if(!btSocket.isConnected()){
try {
btSocket.connect();
} catch (IOException e) {
return new ResultObj(-1,"Socket连接已断开");
}
}
try {
out.write(bytes);
out.flush();
} catch (Exception e) {
return new ResultObj(-1,"OutputStream未创建成功或写出失败");
}
return new ResultObj(1,"请求发送成功");
}

/**
* 蓝牙是否已配对
* @param address
* @return
*/
public ResultObj isConnect(){
if(null != device){
return new ResultObj(1,device.getAddress());
}
return new ResultObj(-1,"蓝牙未连接");
}

/**
* 蓝牙是否开启
* @return
*/
public ResultObj isEnabled(){
if (btAdapt.isEnabled()) {
return new ResultObj(1,"蓝牙已开启");
}else{
return new ResultObj(-1,"蓝牙未开启");
}
}

/**
* 开启蓝牙
* @return
*/
public ResultObj enabled(){
if(!btAdapt.isEnabled()){
btAdapt.enable();
return new ResultObj(1,"蓝牙开启成功");
}
return new ResultObj(-1,"蓝牙开启失败,请重新开启");
}


}

分类:

技术点:

相关文章: