Android开发中编写蓝牙相关功能的核心代码讲解
作者:时之沙 发布时间:2021-07-26 00:24:53
标签:Android,蓝牙
一. 什么是蓝牙(Bluetooth)?
1.1 BuleTooth是目前使用最广泛的无线通信协议
1.2 主要针对短距离设备通讯(10m)
1.3 常用于连接耳机,鼠标和移动通讯设备等.
二. 与蓝牙相关的API
2.1 BluetoothAdapter:
代表了本地的蓝牙适配器
2.2 BluetoothDevice
代表了一个远程的Bluetooth设备
三. 扫描已经配对的蓝牙设备(1)
注:必须部署在真实手机上,模拟器无法实现
首先需要在AndroidManifest.xml 声明蓝牙权限
<user-permission android:name="android.permission.BLUETOOTH" />
配对蓝牙需要手动操作:
1. 打开设置--> 无线网络 --> 蓝牙 勾选开启
2. 打开蓝牙设置 扫描周围已经开启的蓝牙设备(可以与自己的笔记本电脑进行配对),点击进行配对
电脑上会弹出提示窗口: 添加设备
显示计算与设备之间的配对码,要求确认是否配对
手机上也会显示类似的提示.
四. 扫描已经配对的蓝牙设备(2)
4.1 获得BluetoothAdapter对象
4.2 判断当前移动设备中是否拥有蓝牙
4.3 判断当前移动设备中蓝牙是否已经打开
4.4 得到所有已经配对的蓝牙设备对象
蓝牙配对实现的核心代码如下:
MainActivity:
import java.util.Iterator;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.buttonId);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
//获得BluetoothAdapter对象,该API是android 2.0开始支持的
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
//adapter不等于null,说明本机有蓝牙设备
if(adapter != null){
System.out.println("本机有蓝牙设备!");
//如果蓝牙设备未开启
if(!adapter.isEnabled()){
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//请求开启蓝牙设备
startActivity(intent);
}
//获得已配对的远程蓝牙设备的集合
Set<BluetoothDevice> devices = adapter.getBondedDevices();
if(devices.size()>0){
for(Iterator<BluetoothDevice> it = devices.iterator();it.hasNext();){
BluetoothDevice device = (BluetoothDevice)it.next();
//打印出远程蓝牙设备的物理地址
System.out.println(device.getAddress());
}
}else{
System.out.println("还没有已配对的远程蓝牙设备!");
}
}else{
System.out.println("本机没有蓝牙设备!");
}
}
});
}
}
修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备
1. 修改本机蓝牙设备的可见性
2. 扫描周围可用的蓝牙设备
Eg:
一. 清单文件AdroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.se7en"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<!-若需要管理蓝牙设备,如修改可见性,则需以下的权限->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
</manifest>
二. 布局文件: main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/discoverButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="设置可见性"/>
<Button
android:id="@+id/scanButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="开始扫描"/>
</LinearLayout>
三. MainActivity:
import android.app.Activity;
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.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button discoverButton = null;
private Button scanButton = null;
private BluetoothAdapter adapter = null;
private BluetoothReceiver bluetoothReceiver = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter = BluetoothAdapter.getDefaultAdapter();
discoverButton = (Button)findViewById(R.id.discoverButton);
scanButton = (Button)findViewById(R.id.scanButton);
//修改蓝牙设备的可见性
discoverButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
Intent discoverIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//设置蓝牙可见性,500表示可见时间(单位:秒),当值大于300时默认为300
discoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,500);
startActivity(discoverIntent);
}
});
scanButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
//开始扫描周围蓝牙设备,该方法是异步调用并以广播的机制返回,所以需要创建一个BroadcastReceiver来获取信息
adapter.startDiscovery();
}
});
//设定广播接收的filter
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//创建蓝牙广播信息的receiver
bluetoothReceiver = new BluetoothReceiver ();
//注册广播 *
registerReceiver(bluetoothReceiver,intentFilter);
}
private class BluetoothReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//获得扫描到的远程蓝牙设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getAddress());
}
}
}


猜你喜欢
- 多说无益,贴代码:/** * 校验银行卡卡号 * * @param cardId &nbs
- 本文实例讲述了Java获取文件夹下所有文件名称的方法。分享给大家供大家参考,具体如下:import java.io.File;public
- 简介在移动开发中,如果我们要实现一些图像处理相关的功能,难免要用到OpenCV。而OpenCV是用c++开发的。我们在Android中,需要
- DataSource在数据库应用中,客户端与数据库服务端建立的连接对象(Connection)是宝贵的资源,每次请求数据库都创建连接,使用完
- 1.添加加载更多布局1_初始化和隐藏代码在RefreshListView构造方法中调用private void initFooterView
- 如下所示:if(File.Exists(path)){// 是文件}else if(Directory.Exists(path)){// 是
- 目录1 CompletionService介绍2 CompletionService源码分析3 CompletionService实现任务4
- 如果一个项目内有很多个界面,那么在layout下会有太多的activity***.xml文件,这个时候就需要使用文件夹对这些分别存放了。当然
- 本文实例讲述了java统计字符串中重复字符出现次数的方法。分享给大家供大家参考,具体如下:package com;import org.ju
- 一、简介现在的Android应用程序中,不可避免的都会使用到图片,如果每次加载图片的时候都要从网络重新拉取,这样不但很耗费用户的流量,而且图
- 本文实例讲述了java获取中文拼音首字母工具类定义与用法。分享给大家供大家参考,具体如下:package com.sw.documentar
- 一、前言高效、合理的使用hibernate-validator校验框架可以提高程序的可读性,以及减少不必要的代码逻辑。接下来会介绍一下常用一
- public class User { public
- 目录1、备份原数据库File文件2、数据库升级XML编写 updateXml.xml3、创建XML解析器3.1 对应工具类 DomUtils
- /// <summary> /// 队列多线程,T 代表处理的单个类型~&nbs
- 前言在数据结构算法设计中,或者一个方法的具体实现的时候,有一种方法叫做“递归”,这种方法在思想上并不是特别难,但是实现起来还是有一些需要注意
- 本文实例为大家分享了Android读取手机通讯录联系人到项目的具体代码,供大家参考,具体内容如下一、主界面代码如下:<LinearLa
- 本文大纲本文章将要介绍的内容有以下几点,读者朋友也可先自行思考一下相关问题:线程中断 interrupt 方法怎么理解,意思就是线程中断了吗
- 参考 java查找无向连通图中两点间所有路径的算法,对代码进行了部分修改,并编写了测试用例。算法要求:1. 在一个无向连通图中求出
- 这篇文章主要介绍了Java并发CopyOnWrite容器原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值