Android 蓝牙(Bluetooth)(一)

三世轮回 提交于 2020-03-17 08:08:52

Android对于蓝牙开发从2.0版本的sdk才开始支持 Bluetoothadapter,蓝牙开发从4.3版本的sdk才开始支持 BluetoothManagerBluetoothgatt)Android 蓝牙(Bluetooth)(二)

学友资料:Android蓝牙开发浅谈http://www.eoeandroid.com/thread-18993-1-1.html

首先,要操作蓝牙,先要在AndroidManifest.xml里加入权限

<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" /> 

<uses-permissionandroid:name="android.permission.BLUETOOTH" />

 

以下是Bluetoothadapter开发方法:

1.获取本地蓝牙适配器
     BluetoothAdapter mAdapter= BluetoothAdapter.getDefaultAdapter();

2.打开蓝牙
     if (!mAdapter.isEnabled()) {
          // 弹出对话框提示用户是后打开
          Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
          startActivityForResult(enabler, REQUEST_ENABLE);
          // 不做提示,强行打开
          // mAdapter.enable();
     }


3.搜索设备
//1).搜索设备
mAdapter.startDiscovery()
//2)定义BroadcastReceiver,
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//找到设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
Log.v(TAG, "find device:" + device.getName()+ device.getAddress());
}
}
        //搜索完成
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        if (mNewDevicesAdapter.getCount() == 0) {
        Log.v(TAG,"find over");
        }
        }
//执行更新列表的代码
}
};

4.注册BroadcastReceiver,具体代码如下
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);

例子: 

 步骤一:

// 创建一个Socket连接:只需要服务器在注册时的UUID号
device = local.getRemoteDevice(BlueToothAddress);
socket = device.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));

//00001101-0000-1000-8000-00805F9B34FB为设备默认的UUID

  步骤二:

// 启动接受数据
mreadThread = new readThread();
mreadThread.start();

 步骤三:

// 读取数据
private class readThread extends Thread {
public void run() {

byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null;
String tmp = null;
try {
mmInStream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
try {

Log.e("try+++++", "try++++");
// 读取输入流中的数据
if ((bytes = mmInStream.read(buffer)) > 0) {

Log.e("read(buffer)", "数据流--->");
String readMessage = new String(buffer, 0, bytes);
Log.e("readMessage", readMessage);

Formatter fmt3 = new Formatter();
fmt3.format(
" 0~6:%02x %02x %02x %02x %02x %02x %02x 7~18:%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x 19:%02x",
buffer[0], buffer[1], buffer[2], buffer[3],
buffer[4], buffer[5], buffer[6], buffer[7],
buffer[8], buffer[9], buffer[10], buffer[11],
buffer[12], buffer[13], buffer[14], buffer[15],
buffer[16], buffer[17], buffer[18], buffer[19]);
Log.e("返回数据", "fmt3测试 Data:" + fmt3.toString());

  }

}

算法 → byte数组 和 16进制进制见的转换

http://javaman.group.iteye.com/group/wiki/3405-cuisuqiang-google-socket-InputStream-OutputStream

 

private final static byte[] hex = "0123456789ABCDEF".getBytes();

private static int parse(char c) {
    if (c >= 'a')
        return (c - 'a' + 10) & 0x0f;
    if (c >= 'A')
        return (c - 'A' + 10) & 0x0f;
    return (c - '0') & 0x0f;
}
// 从字节数组到十六进制字符串转换
public static String Bytes2HexString(byte[] b) {
    byte[] buff = new byte[2 * b.length];
    for (int i = 0; i < b.length; i++) {
        buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
        buff[2 * i + 1] = hex[b[i] & 0x0f];
    }
    return new String(buff);
}

// 从十六进制字符串到字节数组转换
public static byte[] HexString2Bytes(String hexstr) {
    byte[] b = new byte[hexstr.length() / 2];
    int j = 0;
    for (int i = 0; i < b.length; i++) {
        char c0 = hexstr.charAt(j++);
        char c1 = hexstr.charAt(j++);
        b[i] = (byte) ((parse(c0) << 4) | parse(c1));
    }
    return b;
}

public static void main(String[] args) {
    byte[] bt = new byte[]{10, 2, 12, 14, 1, 0, 0, 1, 0, 31, 45, 1, 8, 0, 1, 0, -96, -45, 10, 3};
    System.out.println(Bytes2HexString(bt));
    System.out.println(Arrays.toString(HexString2Bytes("0A020C0E01000001001F2D0108000100A0D30A03")));
}

打印

0A020C0E01000001001F2D0108000100A0D30A03
[10, 2, 12, 14, 1, 0, 0, 1, 0, 31, 45, 1, 8, 0, 1, 0, -96, -45, 10, 3]

 

// 返回无符号的2进制表示 1110011
String hex = Integer.toBinaryString(115);
System.out.println(hex);
// 返回2进制的字符串1110011对应的值 115
System.out.println(Integer.valueOf("1110011", 2));

// 16进制值转换成二进制
System.out.println(Long.parseLong("49", 16));
System.out.println(Long.parseLong("2F", 16));

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!