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


猜你喜欢
- 一、根据流向分为输入流和输出流:注意输入流和输出流是相对于程序而言的。输出:把程序(内存)中的内容输出到磁盘、光盘等存储设备中输入:读取外部
- service有两种类型:本地服务(Local Service):用于应用程序内部远程服务(Remote Sercie):用于android
- 前言数字时间戳技术是数字签名技术一种变种的应用。是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08
- 一、前言在C#中,由于有了垃圾回收机制的支持,对象的析构和以前的C++有了很大的不同,这就要求程序员在设计类型的时候,充分理解.NET的机制
- 前言Spring Boot项目一般都是内嵌tomcat或者jetty服务器运行,很少用war包部署到外部的服务容器,即使放到linux中,一
- 本文实例为大家分享了Android实现毛玻璃效果弹出菜单动画的具体代码,供大家参考,具体内容如下仿ios上屏幕下方向上滑出来的一个模糊菜单,
- Android使用RecyclerView1. 什么是RecyclerViewRecyclerView 是 Android-support-
- 目录1、Android如何动态更换桌面图标1.1使用场景1.2知识点1.3使用Activity-alias2、巨坑2.1App的覆盖2.2桌
- Service的生命周期 (适用于2.1及以上)1. 被startService的无论是否有任何活动绑定到该Service,都在后台运行。o
- 继上一次利用Servlet实现图片上传,这次利用基于MVC的Struts框架,封装了Servlet并简化了JSP页面跳转。JSP上传页面上传
- 现在许多流行的软件中都有欢迎界面,今天就介绍一下欢迎界面的制作,由于界面涉及到页面的滑动,因此要采用ViewPager,sdk在4.0一下的
- 介绍这里学习SpringSecurity,对SpringSecurity进行学习。基本用法添加依赖<dependency> &n
- 1.概述在平时的开发中,有一些Jar包因为种种原因,在Maven的中央仓库中没有收录,所以就要使用本地引入的方式加入进来。2. 拷贝至项目根
- vs2010测试通过,主要思想是由出生日期和当前日期,两个日期计算出年龄(岁、月、天)using System;using System.C
- 仿Keep运动休息倒计时控件,供大家参考,具体内容如下源码控件本身非常非常简单,唯一难点在于倒计时期间动态增减时长,如果说动态增减时长是瞬间
- 这篇文章主要介绍了跨域解决方案Jsonp原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以
- 一、题目描述题目实现:网络资源的断点续传功能。二、解题思路获取要下载的资源网址显示网络资源的大小上次读取到的字节位置以及未读取的字节数输入下
- 有的时候,我们需要对一堆数据进行统计分析后生成HTML或Excel格式报表。本来这并不是一件很难的事,但确是件比较麻烦的事情。最令人头痛的是
- Android中双击返回键退出程序1.在MyAppliction中(继承Application) //运用list来保存们每一个
- SnackBar是DesignSupportLibrary中的一个重要的控件,用于在界面下面提示一些关键信息,跟Toast不同的地方是Sna