android实现蓝牙app代码
作者:tangzheng828 发布时间:2021-07-08 07:52:15
标签:android,蓝牙,app
本文实例为大家分享了android实现蓝牙app的具体代码,供大家参考,具体内容如下
private BluetoothGatt bluetoothGatt;
private BluetoothGattService gattService;
private BluetoothGattCharacteristic gattCharacteristic;
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private List<BluetoothDevice> devices = new ArrayList<>();
private UUID serviceUUID; //不同设备 不同uuid
private UUID characteristicUUID; //不同设备 不同uuid
private final UUID service4UUID= UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
private final UUID charAUUID = UUID.fromString("0000fffa-0000-1000-8000-00805f9b34fb");
private LightReceiver lightReceiver;
private ScanReceiver scanReceiver;
private ListView listView;
private TextView tvrefresh;
private String lightAction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("tag", "MainActivity onCreate()");
//
listView = (ListView) findViewById(R.id.lv_bluetooth);
tvrefresh = (TextView) findViewById(R.id.tv_refresh_bluetooth);
tvrefresh.setOnClickListener(this);
openBluetooth();
registeLigthReceiver();
registeScanReceiver();
}
@Override
protected void onStart() {
super.onStart();
Log.i("tag", "MainActivity onStart()");
bluetoothScan();
}
//返回
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
Log.i("tag", "MainActivity onKeyUp()");
this.finish();
return super.onKeyUp(keyCode, event);
}
//重新扫描蓝牙
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_refresh_bluetooth:
//蓝牙扫描
bluetoothScan();
break;
default:
break;
}
}
//打开本地蓝牙
private void openBluetooth() {
Log.i("tag", "openLocalBluetooth()");
//检查手机是否支持蓝牙4.0
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "手机不支持蓝牙4.0", Toast.LENGTH_SHORT).show();
finish();
}
//调用系统服务的方式,请求开启蓝牙
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
//开启蓝牙
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
}
//开始蓝牙扫描 扫描到一个添加一个
private void bluetoothScan() {
Log.i("tag", "bluetoothScan()");
if (bluetoothAdapter == null) {
openBluetooth();
}
if (!bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.startDiscovery(); //回调
} else {
Toast.makeText(this, "扫描中..", Toast.LENGTH_SHORT).show();
}
}
//更新蓝牙列表中的数据
private void updateUi() {
Log.i("tag", "updateUi()");
if (devices != null && devices.size() > 0) {
BlueAdapter adapter = new BlueAdapter(this, devices);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(this, "附近没有蓝牙", Toast.LENGTH_SHORT).show();
}
}
//取得gatt 对应的service
private BluetoothGattService getGattService(BluetoothGatt gatt, UUID serviceUUID) {
List<BluetoothGattService> gattServices = gatt.getServices();
for (BluetoothGattService gattService : gattServices) {
if (gattService.getUuid().equals(serviceUUID)) {
return gattService;
}
}
return null;
}
//取得service对应的characteristic
private BluetoothGattCharacteristic getGattCharacteristic(BluetoothGattService gattService, UUID characteristicUUID) {
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
if (gattCharacteristic.getUuid().equals(characteristicUUID)) {
return gattCharacteristic;
}
}
return null;
}
//注册蓝牙扫描监听
private void registeScanReceiver() {
Log.i("tag", "registeScanReceiver()");
scanReceiver = new ScanReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(scanReceiver, filter);
}
//定义蓝牙扫描监听类 添加device , 更新界面
class ScanReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("tag", " BluetoothReceiver / ScanReceiver onReceive() action=" + intent.getAction());
String scanAction = intent.getAction();
if (scanAction.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (!devices.contains(device)) {
devices.add(device);
if (CacheUtils.getBlueDeviceString(MainActivity1.this, device.getAddress()).equals("")) {
CacheUtils.putBlueDeviceString(MainActivity1.this, device.getAddress(), device.getName());
}
updateUi();
}
} else if (scanAction.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
if (devices == null || devices.size() == 0) {
Toast.makeText(MainActivity1.this, "附近没有发现蓝牙设备", Toast.LENGTH_SHORT).show();
}
}
}
}
//注册灯光监听
private void registeLigthReceiver() {
Log.i("tag", "registeReceiver()");
lightReceiver = new LightReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("openLight");
filter.addAction("closeLight");
registerReceiver(lightReceiver, filter);
}
//定义灯控监听类
class LightReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("tag", " BluetoothReceiver /LightReceiver onReceive() action=" + intent.getAction());
//
String address = intent.getStringExtra("bluetoothAddress"); //从adapter取得的数据
lightAction = intent.getAction();
// if() 不同设备 不同serviceUUID,不同的characteristicUUID 自己确定
serviceUUID=service4UUID;
characteristicUUID=charAUUID;
if (bluetoothAdapter == null) {
openBluetooth();
}
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
MyBluetoothGattCallback gattCallback = new MyBluetoothGattCallback();
bluetoothGatt = device.connectGatt(MainActivity1.this, false, gattCallback); //回调
}
}
//蓝牙连接/通信回调
class MyBluetoothGattCallback extends android.bluetooth.BluetoothGattCallback {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
Log.i("tag", "MyBluetoothGattCallback onConnectionStateChange() newState=" + newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.discoverServices(); //连接成功,开始搜索服务,一定要调用此方法,否则获取不到服务
Log.i("tag", "MyBluetoothGattCallback STATE_CONNECTED ");
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i("tag", "MyBluetoothGattCallback STATE_DISCONNECTED");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
Log.i("tag", "MyBluetoothGattCallback onServicesDiscovered() status=" + status);
if (lightAction.equals("openLight") || lightAction.equals("closeLight")) { //避免 不停更新
if (gattService == null || gattCharacteristic == null || !serviceUUID.equals(service4UUID) || !characteristicUUID.equals(charAUUID)) {
gattService = getGattService(gatt, serviceUUID);
if (gattService != null) {
gattCharacteristic = getGattCharacteristic(gattService, characteristicUUID);
if (gattCharacteristic != null) {
gatt.setCharacteristicNotification(gattCharacteristic, true);
gatt.connect();
}
}
}
if (lightAction.equals("openLight")) {
gattCharacteristic.setValue("openLight"); //这里自己设置 蓝牙模组需要的数据
gatt.writeCharacteristic(gattCharacteristic);
} else if (lightAction.equals("closeLight")) {
gattCharacteristic.setValue("closeLight"); //这里自己设置 蓝牙模组需要的数据
gatt.writeCharacteristic(gattCharacteristic);
}
lightAction = "";
gatt.readRemoteRssi();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i("tag", "onDestroy()");
if (bluetoothAdapter != null) {
bluetoothAdapter.disable();
bluetoothAdapter = null;
}
if (bluetoothGatt != null) {
bluetoothGatt.disconnect();
bluetoothGatt.close();
bluetoothGatt = null;
}
if (lightReceiver != null) {
unregisterReceiver(lightReceiver);
lightReceiver = null;
}
if (scanReceiver != null) {
unregisterReceiver(scanReceiver);
scanReceiver = null;
}
}
来源:https://blog.csdn.net/tangzheng828/article/details/52672345
0
投稿
猜你喜欢
- 首先,想要明白hashCode的作用,你必须要先知道Java中的集合。 总的来说,Java中的集合(Collection)有两类,一类是Li
- 前置导入什么是多环境?其实就是说你的电脑上写的程序最终要放到别人的服务器上去运行。每个计算机环境不一样,这就是多环境。常见的多环境开发主要兼
- Android平台有三种网络接口可以使用,他们分别是:java.net.*(标准Java接口)、Org.apache接口和Android.n
- /// <summary> /// 计算本周起始日期(礼拜一的日期) /// </summary&
- 本文介绍了java 读写Parquet格式的数据,分享给大家,具体如下:import java.io.BufferedReader;impo
- 编写程序,利用continue语句实现循环体过滤器,过滤“老鹰”字符串,并做相应的处理,但是放弃continue语句之后的所有代码。即若遇到
- 启动Springboot项目时候报错java: 无法访问org.springframework.boot.SpringApplication
- Java8 HashMap键与Comparable接口最容易使 HashMap 发生哈希冲突的方法是什么呢?我们可以创建一个类,让它的哈希函
- 前言:我们每天都在编写Java代码,编译,执行。很多人已经知道Java源代码文件(.java后缀)会被Java编译器编译为字节码文件(.cl
- Mybatis @SelectKey用法用处主要用来解决主键自增问题用法@SelectKey(statement="SELECT
- 本文实例讲述了Java排序算法总结之希尔排序。分享给大家供大家参考。具体分析如下:前言:希尔排序(Shell Sort)是插入排序的一种。是
- 这篇文章主要介绍了Spring配置文件如何使用${username},文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习
- 哈希表(HashMap)hash查询的时间复杂度是O(1)按值传递Character,Short,Integer,Long, Float,D
- OAuth 2.0 是一种工业级的授权协议。OAuth 2.0是从创建于2006年的OAuth 1.0继承而来的。OAuth 2.0致力于帮
- 棋牌类游戏是目前比较火的游戏之一。今天本文就以实例形式实现洗牌游戏。本文实例所采用的算法是:遍历每个位置上的牌,然后与随机位置上的牌交换。运
- TCPServer 1、使用的通讯通道:socket2、用到的基本功能:①Bind,②Listen,③BeginAccept④En
- 什么是RESTful APIRESTful API是一种基于HTTP协议的Web API,它的设计原则是简单、可扩展、轻量级、可缓存、可靠、
- 产生90-100的重复的随机数:public class RandomTest { public static void main(Str
- 最近一段时间 某台服务器上的一个应用总是隔一段时间就自己挂掉 用top看了看 从重新部署应用开始没有多长时间CPU占用上升得很快排查步骤1.
- 详解 Corba开发之Java实现Service与Client1 概述