布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.hzx.h706.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_con"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="蓝牙连接"/>
<EditText
android:id="@+id/edit_mac"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
android:text="9DA1" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="类型" />
<EditText
android:id="@+id/edit_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="绿色精灵" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="标题" />
<EditText
android:id="@+id/edit_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="张经理:" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="内容" />
<EditText
android:id="@+id/edit_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="小蔡,今天晚上请吃饭,老地方见!" />
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送数据"/>
</LinearLayout>
activity
package com.example.hzx.h706;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final UUID SERVIE_UUID = UUID.fromString("0000ffb0-0000-1000-8000-00805f9b34fb");
private static final UUID CHARACTERISTIC_UUID_WRITE = UUID.fromString( "0000ffb1-0000-1000-8000-00805f9b34fb");
private static final UUID CHARACTERISTIC_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
private final String TAG = "123";
private Button btn_con;
private Button btn_send;
private Boolean is_con = false;
private String BleDeviceMac = "E6:71:15:9D:9D:A1";
//蓝牙相关的
//获取系统蓝牙适配器管理类
private BluetoothAdapter mBluetoothAdapter = null;
BluetoothDevice targetDevice = null;
private BluetoothGatt mBluetoothGatt = null;
private BluetoothGattService service = null;
private BluetoothGattCharacteristic writeCharacteristic=null;
// 申请打开蓝牙请求的回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "蓝牙已经开启", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "没有蓝牙权限", Toast.LENGTH_SHORT).show();
finish();
}
}
}
public void SendDataToBle(String data){
if (( writeCharacteristic==null ) || (mBluetoothGatt == null)){
return;
}
byte[] byteArray = new byte[30];
byteArray = DigitalConver.toByteArray(data);
Log.d(TAG,""+data);
writeCharacteristic.setValue(byteArray);
mBluetoothGatt.writeCharacteristic(writeCharacteristic);
}
public boolean setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.e(TAG, "BluetoothAdapter not initialized");
return false;
}
boolean b = mBluetoothGatt.setCharacteristicNotification(characteristic, true);
if (b){
Log.e(TAG, "打开通知成功");
}
Log.e(TAG, "写入数据到描述符");
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CHARACTERISTIC_DESCRIPTOR_UUID);
if (descriptor == null) {
return false;
}
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
}
mBluetoothGatt.writeDescriptor(descriptor);
return true;
}
private BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) {
String string = "H706";
if (string.equals(device.getName()))
{
Log.d(TAG, "" + device.getName());
Log.d(TAG,""+device.getAddress());
if (BleDeviceMac.equals(device.getAddress()) ) {
//停止扫描
targetDevice = device;
Log.d(TAG,"find deviec....");
mBluetoothAdapter.stopLeScan(callback);
Log.d(TAG,"开始连接设备");
mBluetoothGatt = targetDevice.connectGatt(MainActivity.this, false, gattCallback);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_con = (Button)findViewById(R.id.btn_con);
btn_con.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG,"btn_con-------->");
if (false == is_con){
if (mBluetoothAdapter == null){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
// 询问打开蓝牙
if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
Log.d(TAG,"start scan-------->");
if (callback==null) {
Log.d(TAG,"callback=null-------->");
}
//扫描设备
mBluetoothAdapter.startLeScan(callback);
}
}
});
btn_send = (Button)findViewById(R.id.btn_send);
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (true == is_con){
SendDataToBle("B21303020202");
//setCharacteristicNotification(writeCharacteristic,true);
}
}
});
}
private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothGatt.STATE_CONNECTED) {
Log.e(TAG, "设备连接上 开始扫描服务");
// 开始扫描服务,安卓蓝牙开发重要步骤之一
mBluetoothGatt.discoverServices();
}
if (newState == BluetoothGatt.STATE_DISCONNECTED) {
Log.e(TAG, "蓝牙断开");
is_con = false;
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
//获取服务列表
String uuid;
Log.e(TAG, "获取服务列表1");
service = mBluetoothGatt.getService(SERVIE_UUID);
Log.e(TAG, "获取特征值1");
writeCharacteristic = service.getCharacteristic(CHARACTERISTIC_UUID_WRITE);
Log.e(TAG, "打开通知2");
setCharacteristicNotification(writeCharacteristic,true);
Log.e(TAG, "蓝牙设置完毕3");
is_con = true;
}
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorRead(gatt, descriptor, status);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
Log.e(TAG, "写成功");
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
if ( status == BluetoothGatt.GATT_SUCCESS ) {
Log.e(TAG, "真开启监听成功");
}else{
Log.e(TAG, "假开启监听成功");
}
};
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.e(TAG,"蓝牙收到数据--------->");
byte[] value = characteristic.getValue();
String string;
string = DigitalConver.formatData(value);
Log.e(TAG,"vale:"+string);
}
};
}
转化数据的类
package com.example.hzx.h706;
/**
* Created by hzx on 2019/1/14.
*/
public class DigitalConver {
/**
* @Date 2017/5/10
* @Author wenzheng.liu
* @Description 格式化数据
*/
public static String formatData(byte[] data) {
if (data != null && data.length > 0) {
StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(byte2HexString(byteChar));
//LogModule.i(stringBuilder.toString());
return stringBuilder.toString();
}
return null;
}
/**
* @Date 2017/5/10
* @Author wenzheng.liu
* @Description byte转16进制
*/
public static String byte2HexString(byte b) {
return String.format("%02X ", b);
}
/**
* @Date 2017/5/15
* @Author wenzheng.liu
* @Description 16进制转10进制
*/
public static String decodeToString(String data) {
String string = Integer.toString(Integer.parseInt(data, 16));
return string;
}
/**
* @Date 2017/5/16
* @Author wenzheng.liu
* @Description 16进制转2进制
*/
public static String hexString2binaryString(String hexString) {
if (hexString == null || hexString.length() % 2 != 0)
return null;
String bString = "", tmp;
for (int i = 0; i < hexString.length(); i++) {
tmp = "0000"
+ Integer.toBinaryString(Integer.parseInt(
hexString.substring(i, i + 1), 16));
bString += tmp.substring(tmp.length() - 4);
}
return bString;
}
/**
* @Date 2017/6/2
* @Author wenzheng.liu
* @Description 16进制数组转byte数组
*/
public static byte[] hexStringArray2byteArray(String[] hexString) {
byte[] data = new byte[hexString.length];
for (int i = 0; i < hexString.length; i++) {
data[i] = (byte) Integer.parseInt(hexString[i], 16);
}
return data;
}
/**
* To byte array byte [ ].
*
* @param hexString the hex string
* @return the byte [ ]
*/
public static byte[] toByteArray(String hexString) {
/*
if (StringUtils.isEmpty(hexString))
return null;
*/
hexString = hexString.toLowerCase();
final byte[] byteArray = new byte[hexString.length() >> 1];
int index = 0;
for (int i = 0; i < hexString.length(); i++) {
if (index > hexString.length() - 1)
return byteArray;
byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
byteArray[i] = (byte) (highDit << 4 | lowDit);
index += 2;
}
return byteArray;
}
/**
* byte[] to Hex string.
*
* @param byteArray the byte array
* @return the string
*/
public static String toHexString(byte[] byteArray) {
final StringBuilder hexString = new StringBuilder("");
if (byteArray == null || byteArray.length <= 0)
return null;
for (int i = 0; i < byteArray.length; i++) {
int v = byteArray[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
hexString.append(0);
}
hexString.append(hv);
}
return hexString.toString().toLowerCase();
}
}
效果
image.png
网友评论