Android学习笔记之蓝牙功能
作者:RKGG爱吃鱼 发布时间:2022-05-19 05:07:44
标签:Android,蓝牙
本文实例为大家分享了Android学习笔记之蓝牙功能的具体代码,供大家参考,具体内容如下
蓝牙:短距离无线通讯技术标准。蓝牙协议分为4层,即核心协议层、电缆替代协议层、电话控制协议层和其他协议层。其中核心协议层包括基带、链路管理、逻辑链路控制和适应协议四部分。链路管理(LMP)负责蓝牙组件间的建立。逻辑链路控制与适应协议(L2CAP)位于基带协议层上,属于数据链路层,是一个高层传输和应用层协议屏蔽基带协议的适配协议。
1)、第一种打开蓝牙的方式:
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,1);
2)、第二种打开蓝牙方式(静默)
权限配置:
<uses-permission android:name=”android.permission.BLUETOOTH”/>
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/>
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.enable();//打开
adapter.disable();//关闭
3)、通过代码搜索蓝牙
蓝牙数据传输:与Socket类似,网络中使用Socket和ServerSocket控制客户端和服务端,蓝牙通讯客户端为BluetoothSocket,服务端为BluetoothServerSocket。二者需要一个UUID(全局唯一标示符),格式如下:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX,被分为5段,其中3段字符数相同,都为4,第1段是8字符,最后一段12字符,UUID相当于Socket的端口,而蓝牙地址相当于Socket的IP。
一、搜索蓝牙设备
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private TextView tvDevices;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
tvDevices = (TextView) findViewById(R.id.tvDevices);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> paireDevices = bluetoothAdapter.getBondedDevices();
if (paireDevices.size()>0){
for (BluetoothDevice devices:paireDevices){
tvDevices.append(devices.getName()+":"+devices.getAddress());
}
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//找到一个设备,发送一个广播
this.registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//整个搜索完后发送广播
this.registerReceiver(receiver,filter);
}
public void onClick_Search(View view){
setProgressBarIndeterminateVisibility(true);
setTitle("正在扫描...");
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
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) {
tvDevices.append(device.getName() + ":" + device.getAddress() + "\n");
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarVisibility(false);
setTitle("搜索完成");
}
}
};
}
真机测试效果图:
二、通过搜索,将搜到的设备连接并实现传输数据
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private BluetoothAdapter bluetoothAdapter;//蓝牙适配器
private ListView lvDevices;//显示蓝牙搜索控件
private List<String> bluetoothDevices = new ArrayList<String>();//存储搜索到的所有蓝牙设备
private ArrayAdapter<String> arrayAdapter;
private final UUID MY_UUID = UUID.fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3");//手动输入UUID码
private final String NAME = "Bluetooth_Socket";
private BluetoothSocket clientSocket;//服务端
private BluetoothDevice device;
private OutputStream os;
private AcceptThread acceptThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//初始化
lvDevices = (ListView) findViewById(R.id.lvDevices);
//显示配对的蓝牙信息
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
bluetoothDevices.add(device.getName() + ":" + device.getAddress() + "\n");
}
}
//显示设备在列表上
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, bluetoothDevices);
lvDevices.setAdapter(arrayAdapter);
lvDevices.setOnItemClickListener(this);
acceptThread = new AcceptThread();
acceptThread.start();
}
public void onClick_Search(View view) {
setProgressBarIndeterminateVisibility(true);
setTitle("正在扫描...");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
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) {
bluetoothDevices.add(device.getName()+":"+device.getAddress()+"\n");
arrayAdapter.notifyDataSetChanged();
// tvDevices.append(device.getName() + ":" + device.getAddress() + "\n");
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle("连接蓝牙设备");
}
}
};
/*
* 客户端设置
* 单击事件
* */
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = arrayAdapter.getItem(position);
String address = s.substring(s.indexOf(":") + 1).trim();//获取蓝牙IP
try {
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();//若当前蓝牙被使用,则关闭重新启用
}
try {
if (device == null) {//若未连接,则获得远程设备
device = bluetoothAdapter.getRemoteDevice(address);
}
if (clientSocket == null) {
clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
clientSocket.connect();//连接蓝牙
os = clientSocket.getOutputStream();//客户端向服务端输出文本
}
} catch (IOException e) {
e.printStackTrace();
}
if (os != null) {
os.write("发送信息到其他设备".getBytes("utf-8"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 服务端设置
* 设置一个Handler,用来显示
* */
private android.os.Handler handler = new android.os.Handler() {
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, String.valueOf(msg.obj), Toast.LENGTH_LONG).show();
super.handleMessage(msg);
}
};
//线程类
private class AcceptThread extends Thread {
private BluetoothServerSocket serverSocket;
private BluetoothSocket socket;
private InputStream is;
private OutputStream os;
public AcceptThread() {
try {
serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
socket = serverSocket.accept();
is = socket.getInputStream();
os = socket.getOutputStream();
while (true) {
byte[] buffer = new byte[128];
int count = is.read(buffer);
Message msg = new Message();
msg.obj = new String(buffer, 0, count, "utf-8");
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
真机测试效果图:
来源:https://blog.csdn.net/xiaoxun2802/article/details/62043591


猜你喜欢
- 本文以实例形式讲述了C#泛型的用法,有助于读者深入理解C#泛型的原理,具体分析如下:首先需要明白什么时候使用泛型:当针对不同的数据类型,采用
- 一. String类简介1. 介绍字符串广泛应用 在 Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来
- 正常情况下,我们是直接去string的length的,但是汉字是有两个字节的,所以直接用length是错的。如下图:所以应该用以下代码来获取
- 1.Jquery验证1)引入头文件<script src="../../Scripts/jquery-1.7.1.js&qu
- java 弹幕小游戏的最初版本,供大家参考,具体内容如下最近在学习javaSE,根据b站视频老师的讲解,也参考了他的代码,做了一个弹幕小游戏
- 1、什么是 IOC?IOC-Inversion of Control,即控制反转。它不是什么技术,而是一种设计思想。传统的创建对象的方法是直
- 基本使用使用WebView通常是需要网络的,所以需要加上访问网络的权限<uses-permission android:name=&q
- Chart控件可以用来绘制波形图、柱状图、饼图、折线图等,用来进行数据表现是很不错的简单说一下这个控件的使用方法效果图我们首先要加载Char
- Android RecyclerView 是Android5.0推出来的,导入support-v7包即可使用。个人体验来说,Recycler
- 分页问题是一个非常普遍的问题,开发者几乎都会遇到,这里不讨论具体如何分页,说明一下Web方式下分页的原理。首先是查询获得一个结果集(表现为查
- 冒泡排序:就是按索引逐次比较相邻的两个元素,如果大于/小于(取决于需要升序排还是降序排),则置换,否则不做改变这样一轮下来,比较了n-1次,
- 在开发中,我们经常使用到ListView这个控件。Android的API也提供了许多创建ListView适配器的快捷方式。例如A
- SpringMVC文件上传中要解决的问题一、中文文件名编码问题通过过滤器解决二、文件位置存储问题放在当前项目下,作为静态资源,这样可以通过U
- 1. web.xml中配置了CharacterEncodingFilter,配置这个是拦截所有的资源并设置好编号格式。encoding设置成
- 本文实例讲述了C#实现解压GZip文件的方法。分享给大家供大家参考。具体实现方法如下:public void ungzip(string p
- 一、前言代码死循环这个话题,个人觉得还是挺有趣的。因为只要是开发人员,必定会踩过这个坑。如果真的没踩过,只能说明你代码写少了,或者是真正的大
- 上篇文章我们已经可以在 Grafana 上看到对应的 SpringBoot 应用信息了,通过这些信息我们可以对 SpringBoot 应用有
- 一、项目运行环境配置:Jdk1.8 + Tomcat8.5 + Mysql + HBuilderX(Webstorm也行)+ Eclispe
- 把bitmap图片的某一部分的颜色改成其他颜色private Bitmap ChangeBitmap(Bitmap bitmap){ int
- 苹果的iphone 有语音识别用的是Google 的技术,做为Google 力推的Android 自然会将其核心技术往Android 系统里