当前位置:首页 » 安卓系统 » android蓝牙开发

android蓝牙开发

发布时间: 2022-01-11 12:20:25

1. android 蓝牙开发 ble 难吗

还是比较难的,只有不断学习了、
在Google I/O开发者年会上,Google宣布未来几个月内其Android操作系统将全面支持Bluetooth Smart Ready和 Bluetooth Smart设备。
采用新版Android系统的移动电话和平板,只要搭载双模蓝牙芯片即属于Bluetooth Smart Ready规格。Bluetooth Smart Ready是蓝牙技术的进阶标准,几乎可与所有支持蓝牙技术的电子产品兼容,包括键盘、耳机,以及超级省电的下一代Bluetooth Smart智能应用配件(Bluetooth Smart appcessory),如FitBit Flex智能腕带及Pebble智能手表等。

2. android 蓝牙 开发问题

public boolean setName(String name)
Set the friendly Bluetooth name of the local Bluetoth adapter.
This name is visible to remote Bluetooth devices.
Valid Bluetooth names are a maximum of 248 UTF-8 characters, however many
remote devices can only display the first 40 characters, and some may be limited
to just 20.

文档中不是有说明吗!
最大有效值是用utf-8编码的248个字符,然而有些蓝牙设备最多能显示40个字符,....20char。

3. 如何使用Android蓝牙开发

Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输。本文档描述了怎样利用android平台提供的蓝牙API去实现蓝压设备之间的通信。蓝牙具有point-to-point 和 multipoint两种连接功能。
使用蓝牙API,可以做到:
* 搜索蓝牙设备
* 从本地的Bluetooth adapter中查询已经配对的设备
* 建立RFCOMM通道
* 通过service discovery连接到其它设备
* 在设备之间传输数据
* 管理多个连接

基础知识
本文档介绍了如何使用Android的蓝牙API来完成的四个必要的主要任务,使用蓝牙进行设备通信,主要包含四个部分:蓝牙设置、搜索设备(配对的或可见的)、连接、传输数据。
所有的蓝牙API在android.bluetooth包中。实现这些功能主要需要下面这几个类和接口:

BluetoothAdapter
代表本地蓝牙适配器(蓝牙发射器),是所有蓝牙交互的入口。通过它可以搜索其它蓝牙设备,查询已经配对的设备列表,通过已知的MAC地址创建BluetoothDevice,创建BluetoothServerSocket监听来自其它设备的通信。

BluetoothDevice
代表了一个远端的蓝牙设备, 使用它请求远端蓝牙设备连接或者获取 远端蓝牙设备的名称、地址、种类和绑定状态。 (其信息是封装在 bluetoothsocket 中) 。

BluetoothSocket
代表了一个蓝牙套接字的接口(类似于 tcp 中的套接字) ,他是应用程 序通过输入、输出流与其他蓝牙设备通信的连接点。

BluetoothServerSocket
代表打开服务连接来监听可能到来的连接请求 (属于 server 端) , 为了连接两个蓝牙设备必须有一个设备作为服务器打开一个服务套接字。 当远端设备发起连 接连接请求的时候,并且已经连接到了的时候,Blueboothserversocket 类将会返回一个 bluetoothsocket。

BluetoothClass
描述了一个设备的特性(profile)或该设备上的蓝牙大致可以提供哪些服务(service),但不可信。比如,设备是一个电话、计算机或手持设备;设备可以提供audio/telephony服务等。可以用它来进行一些UI上的提示。
BluetoothProfile

BluetoothHeadset
提供手机使用蓝牙耳机的支持。这既包括蓝牙耳机和免提(V1.5)模式。

BluetoothA2dp
定义高品质的音频,可以从一个设备传输到另一个蓝牙连接。 “A2DP的”代表高级音频分配模式。

BluetoothHealth
代表了医疗设备配置代理控制的蓝牙服务

BluetoothHealthCallback
一个抽象类,使用实现BluetoothHealth回调。你必须扩展这个类并实现回调方法接收更新应用程序的注册状态和蓝牙通道状态的变化。

4. android 4.0 蓝牙开发 怎么入手

本文介绍Android ble 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用,如果手机系统版本API level < 18,也是用不了蓝牙4.0的哦。

首先发一下官方的demo,有兴趣的可以过去看看:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html。android系统4.3以上,手机支持蓝牙4.0,具有搜索,配对,连接,发现服务及特征值,断开连接等功能,下载地址:http://download.csdn.net/detail/lqw770737185/8116019。

一、了解api及概念

1.1 BluetoothGatt

继承BluetoothProfile,通过BluetoothGatt可以连接设备(connect),发现服务(discoverServices),并把相应地属性返回到BluetoothGattCallback

1.2 BluetoothGattCharacteristic

相当于一个数据类型,它包括一个value和0~n个value的描述(BluetoothGattDescriptor)

1.3 BluetoothGattDescriptor

描述符,对Characteristic的描述,包括范围、计量单位等

1.4 BluetoothGattService

服务,Characteristic的集合。

1.5 BluetoothProfile

一个通用的规范,按照这个规范来收发数据。

1.6 BluetoothManager

通过BluetoothManager来获取BluetoothAdapter

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
1.7 BluetoothAdapter

一个Android系统只有一个BluetoothAdapter ,通过BluetoothManager 获取

BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
1.8 BluetoothGattCallback

已经连接上设备,对设备的某些操作后返回的结果。这里必须提醒下,已经连接上设备后的才可以返回,没有返回的认真看看有没有连接上设备。

private BluetoothGattCallback GattCallback = new BluetoothGattCallback() {
// 这里有9个要实现的方法,看情况要实现那些,用到那些就实现那些
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){};
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){};
};
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BluetoothGatt gatt = device.connectGatt(this, false, mGattCallback);
1.8.1:notification对应onCharacteristicChanged;

gatt.setCharacteristicNotification(characteristic, true);
1.8.2:readCharacteristic对应onCharacteristicRead;

gatt.readCharacteristic(characteristic);
1.8.3: writeCharacteristic对应onCharacteristicWrite;

gatt.wirteCharacteristic(mCurrentcharacteristic);
1.8.4:连接蓝牙或者断开蓝牙 对应 onConnectionStateChange;

1.8.5: readDescriptor对应onDescriptorRead;

1.8.6:writeDescriptor对应onDescriptorWrite;

gatt.writeDescriptor(descriptor);
1.8.7:readRemoteRssi对应onReadRemoteRssi;

gatt.readRemoteRssi()
1.8.8:executeReliableWrite对应onReliableWriteCompleted;

1.8.9:discoverServices对应onServicesDiscovered。

gatt.discoverServices()
1.9 BluetoothDevice

扫描后发现可连接的设备,获取已经连接的设备

二、开启蓝牙权限

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
如果 android.hardware.bluetooth_le设置为false,可以安装在不支持的设备上使用,判断是否支持蓝牙4.0用以下代码就可以了

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "设备不支持蓝牙4.0", Toast.LENGTH_SHORT).show();
finish();
}
三、对蓝牙的启动关闭操作

1、利用系统默认开启蓝牙对话框

if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
2、后台打开蓝牙,不做任何提示,这个也可以用来自定义打开蓝牙对话框啦

mBluetoothAdapter.enable();
3、后台关闭蓝牙

mBluetoothAdapter.disable();
四、扫描设备,连接设备,获取设备信息 ,断开连接设备,自行查看官方demo,还是看demo比较清晰啊

5. 安卓开发 蓝牙 后台

用一个service

java">//获取适配器BluetoothAdaptermAdapter=BluetoothAdapter.getDefaultAdapter();
//不做提示,强行打开
if(!mAdapter.isEnabled()){
mAdapter.enable();
}
BroadcastReceivermReceiver=newBroadcastReceiver(){
publicvoidonReceive(Contextcontext,Intentintent){
Stringaction=intent.getAction();
//找到设备
if(BluetoothDevice.ACTION_FOUND.equals(action)){

BluetoothDevicedevice=intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(device.getBondState()!=BluetoothDevice.BOND_BONDED){


}

}

//搜索完成

elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)){
if(mNewDevicesAdapter.getCount()==0){

Log.v(TAG,"findover");

}

}
//执行更新列表的代码后台这里就不需要更新
}
};

//注册广播接收者
IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,filter);
filter=newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver,filter);
//这样就可以获取到所有的连接对象了然后在里面选择一个制定的mac地址使用
BluetoothSocketclienSocket=dcvice.(UUID);
clienSocket.connect();
inputStream=socket.getInputStream();
//将对象设备看作服务端然后get出流再将流转化成字符串就可以判断服务端发出的命令了这些都可以在service中完成纯手打如有相同答案请看清楚时间先后杜绝抄袭!望楼主采纳!~

6. Android蓝牙开发代码怎么写

开启蓝牙设备和设置可见时间:

privatevoidsearch(){
BluetoothAdapteradapter=BluetoothAdapter.getDefaultAdapter();
if(!adapter.isEnabled()){
adapter.enable();
}
Intentenable=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,3600);//3600为蓝牙设备可见时间
startActivity(enable);
IntentsearchIntent=newIntent(this,ComminuteActivity.class);
startActivity(searchIntent);
}

首先,需要获得一个BluetoothAdapter,可以通过getDefaultAdapter()获得系统默认的蓝牙适配器,当然我们也可以自己指定,但这个真心没有必要,至少我是不需要的。然后我们检查手机的蓝牙是否打开,如果没有,通过enable()方法打开。接着我们再设置手机蓝牙设备的可见,可见时间可以自定义。

http://www.cnblogs.com/wenjiang/p/3200138.html

7. Android蓝牙开发怎么检查远程蓝牙设备是否打开

通过下面的代码判断蓝牙是否链接:
BluetoothHeadset mBluetoothHeadset;

// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);

// Define Service Listener of BluetoothProfile
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = (BluetoothHeadset) proxy;
}
}
public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null;
}
}
};

//call functions on mBluetoothHeadset to check if Bluetooth SCO audio is connected.
List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
for ( final BluetoothDevice dev : devices ) {
return mBluetoothHeadset.isAudioConnected(dev);
}

// finally Close proxy connection after use.
mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);

8. android蓝牙开发,PC端模拟串口接收字符,该如何编程

您好,android蓝牙这方面还是很好搞的,因为大家的方式都是差不多的。先说说如何开启蓝牙设备和设置可见时间:

private void search() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (!adapter.isEnabled()) {
adapter.enable();
}
Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600); //3600为蓝牙设备可见时间
startActivity(enable);
Intent searchIntent = new Intent(this, ComminuteActivity.class);
startActivity(searchIntent);
}

首先,需要获得一个BluetoothAdapter,可以通过getDefaultAdapter()获得系统默认的蓝牙适配器,当然我们也可以自己指定,但这个真心没有必要,至少我是不需要的。然后我们检查手机的蓝牙是否打开,如果没有,通过enable()方法打开。接着我们再设置手机蓝牙设备的可见,可见时间可以自定义。

完成这些必要的设置后,我们就可以正式开始与蓝牙模块进行通信了:

public class ComminuteActivity extends Activity {
private BluetoothReceiver receiver;
private BluetoothAdapter bluetoothAdapter;
private List<String> devices;
private List<BluetoothDevice> deviceList;
private Bluetooth client;
private final String lockName = "BOLUTEK";
private String message = "000001";
private ListView listView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);

listView = (ListView) this.findViewById(R.id.list);
deviceList = new ArrayList<BluetoothDevice>();
devices = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver = new BluetoothReceiver();
registerReceiver(receiver, filter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setContentView(R.layout.connect_layout);
BluetoothDevice device = deviceList.get(position);
client = new Bluetooth(device, handler);
try {
client.connect(message);
} catch (Exception e) {
Log.e("TAG", e.toString());
}
}
});
}

@Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}

private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Bluetooth.CONNECT_FAILED:
Toast.makeText(ComminuteActivity.this, "连接失败", Toast.LENGTH_LONG).show();
try {
client.connect(message);
} catch (Exception e) {
Log.e("TAG", e.toString());
}
break;
case Bluetooth.CONNECT_SUCCESS:
Toast.makeText(ComminuteActivity.this, "连接成功", Toast.LENGTH_LONG).show();
break;
case Bluetooth.READ_FAILED:
Toast.makeText(ComminuteActivity.this, "读取失败", Toast.LENGTH_LONG).show();
break;
case Bluetooth.WRITE_FAILED:
Toast.makeText(ComminuteActivity.this, "写入失败", Toast.LENGTH_LONG).show();
break;
case Bluetooth.DATA:
Toast.makeText(ComminuteActivity.this, msg.arg1 + "", Toast.LENGTH_LONG).show();
break;
}
}
};

private class BluetoothReceiver extends 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 (isLock(device)) {
devices.add(device.getName());
}
deviceList.add(device);
}
showDevices();
}
}

private boolean isLock(BluetoothDevice device) {
boolean isLockName = (device.getName()).equals(lockName);
boolean isSingleDevice = devices.indexOf(device.getName()) == -1;
return isLockName && isSingleDevice;
}

private void showDevices() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
devices);
listView.setAdapter(adapter);
}
}

9. 如何使用Android蓝牙开发

转载 Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输。本文档描述了怎样利用android平台提供的蓝牙API去实现蓝压设备之间的通信。蓝牙具有point-to-point 和 multipoint两种连接功能。
使用蓝牙API,可以做到:
* 搜索蓝牙设备
* 从本地的Bluetooth adapter中查询已经配对的设备
* 建立RFCOMM通道
* 通过service discovery连接到其它设备
* 在设备之间传输数据
* 管理多个连接

基础知识
本文档介绍了如何使用Android的蓝牙API来完成的四个必要的主要任务,使用蓝牙进行设备通信,主要包含四个部分:蓝牙设置、搜索设备(配对的或可见的)、连接、传输数据。
所有的蓝牙API在android.bluetooth包中。实现这些功能主要需要下面这几个类和接口:

BluetoothAdapter
代表本地蓝牙适配器(蓝牙发射器),是所有蓝牙交互的入口。通过它可以搜索其它蓝牙设备,查询已经配对的设备列表,通过已知的MAC地址创建BluetoothDevice,创建BluetoothServerSocket监听来自其它设备的通信。

BluetoothDevice
代表了一个远端的蓝牙设备, 使用它请求远端蓝牙设备连接或者获取 远端蓝牙设备的名称、地址、种类和绑定状态。 (其信息是封装在 bluetoothsocket 中) 。

BluetoothSocket
代表了一个蓝牙套接字的接口(类似于 tcp 中的套接字) ,他是应用程 序通过输入、输出流与其他蓝牙设备通信的连接点。

BluetoothServerSocket
代表打开服务连接来监听可能到来的连接请求 (属于 server 端) , 为了连接两个蓝牙设备必须有一个设备作为服务器打开一个服务套接字。 当远端设备发起连 接连接请求的时候,并且已经连接到了的时候,Blueboothserversocket 类将会返回一个 bluetoothsocket。

BluetoothClass
描述了一个设备的特性(profile)或该设备上的蓝牙大致可以提供哪些服务(service),但不可信。比如,设备是一个电话、计算机或手持设备;设备可以提供audio/telephony服务等。可以用它来进行一些UI上的提示。
BluetoothProfile

BluetoothHeadset
提供手机使用蓝牙耳机的支持。这既包括蓝牙耳机和免提(V1.5)模式。

BluetoothA2dp
定义高品质的音频,可以从一个设备传输到另一个蓝牙连接。 “A2DP的”代表高级音频分配模式。

BluetoothHealth
代表了医疗设备配置代理控制的蓝牙服务

BluetoothHealthCallback
一个抽象类,使用实现BluetoothHealth回调。你必须扩展这个类并实现回调方法接收更新应用程序的注册状态和蓝牙通道状态的变化。


代表一个应用程序的配置,蓝牙医疗第三方应用注册与远程蓝牙医疗设备交流。

BluetoothProfile.ServiceListener
当他们已经连接到或从服务断开时通知BluetoothProfile IPX的客户时一个接口(即运行一个特定的配置文件,内部服务)。

蓝牙权限
为了在你的应用中使用蓝牙功能,至少要在AndroidManifest.xml中声明两个权限:BLUETOOTH(任何蓝牙相关API都要使用这个权限) 和 BLUETOOTH_ADMIN(设备搜索、蓝牙设置等)。

为了执行蓝牙通信,例如连接请求,接收连接和传送数据都必须有BLUETOOTH权限。

必须要求BLUETOOTH_ADMIN的权限来启动设备发现或操纵蓝牙设置。大多数应用程序都需要这个权限能力,发现当地的蓝牙设备。此权限授予其他的能力不应该使用,除非应用程序是一个“电源管理”,将根据用户要求修改的蓝牙设置

注释:要请求BLUETOOTH_ADMIN的话,必须要先有BLUETOOTH。

在你的应用manifest 文件中声明蓝牙权限。例如:

<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
...
</manifest>
通过查看<uses-permission>资料来声明应用权限获取更多的信息。

蓝牙设置
在你的应用通过蓝牙进行通信之前,你需要确认设备是否支持蓝牙,如果支持,确信它被打开。

如果不支持,则不能使用蓝牙功能。如果支持蓝牙,但不能够使用,你刚要在你的应用中请求使用蓝牙。这个要两步完成,使用BluetoothAdapter。

1.获取BluetoothAdapter

所有的蓝牙活动请求BluetoothAdapter,为了获取BluetoothAdapter,呼叫静态方法getDefaultAdapter() 。这个会返回一个BluetoothAdapter,代表设备自己的蓝牙适配器(蓝牙无线电)。这个蓝牙适配器应用于整个系统中,你的应用可以通过这个对象进行交互。如果getDefaultAdapter()返回null,则这个设备不支持蓝牙。例如:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
2.打开蓝牙

其次。你需要确定蓝牙能够使用。通过isEnabled()来检查蓝牙当前是否可用。如果这个方法返回false,则蓝牙不能够使用。为了请求蓝牙使用,呼叫startActivityForResult()与的ACTION_REQUEST_ENABLE动作意图。通过系统设置中启用蓝牙将发出一个请求(不停止蓝牙应用)。例如:

if (mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
![http://developer.android.com/images/bt_enable_request.png]

对话框中显示请求使用蓝牙权限。如果响应"Yes",这个进程完成(或失败)后你的应用将能够使用蓝牙。
REQUEST_ENABLE_BT常量作为一个整型传到startActivityForResult()中(值必须大于0),该系统传回给你,在你onActivityResult()作为实现的requestCode参数。

如果调用蓝牙成功,你的Activity就会在onActivityResult()中收到RESULT_OK结果,如果蓝牙不能使用由于错误(或用户响应“NO”那么结果返回RESULT_CANCELED。

除了通过onActivityResult(),还可以通过监听ACTION_STATE_CHANGED这个broadcast Intent来知道蓝牙状态是否改变。这个Intent包含EXTRA_STATE,EXTRA_PREVIOUS_STATE两个字段,分别代表新旧状态。可能的值是STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF, 还有STATE_OFF。

小贴: Enabling discoverability 将自动启用蓝牙。如果您计划执行蓝牙活动之前,始终使设备可发现,你可以跳过上面的步骤2。参阅enabling discoverability。

搜索设备
使用BluetoothAdapter可以通过设备搜索或查询配对设备找到远程Bluetooth设备。

Device discovery(设备搜索)是一个扫描搜索本地已使能Bluetooth设备并且从搜索到的设备请求一些信息的过程(有时候会收到类似“discovering”,“inquiring”或“scanning”)。但是,搜索到的本地Bluetooth设备只有在打开被发现功能后才会响应一个discovery请求,响应的信息包括设备名,类,唯一的MAC地址。发起搜寻的设备可以使用这些信息来初始化跟被发现的设备的连接。
一旦与远程设备的第一次连接被建立,一个pairing请求就会自动提交给用户。如果设备已配对,配对设备的基本信息(名称,类,MAC地址)就被保存下来了,能够使用Bluetooth API来读取这些信息。使用已知的远程设备的MAC地址,连接可以在任何时候初始化而不必先完成搜索(当然这是假设远程设备是在可连接的空间范围内)。

需要记住,配对和连接是两个不同的概念:

配对意思是两个设备相互意识到对方的存在,共享一个用来鉴别身份的链路键(link-key),能够与对方建立一个加密的连接。

连接意思是两个设备现在共享一个RFCOMM信道,能够相互传输数据。

目前Android Bluetooth API's要求设备在建立RFCOMM信道前必须配对(配对是在使用Bluetooth API初始化一个加密连接时自动完成的)。

下面描述如何查询已配对设备,搜索新设备。

注意:Android的电源设备默认是不能被发现的。用户可以通过系统设置让它在有限的时间内可以被发现,或者可以在应用程序中要求用户使能被发现功能。

查找匹配设备
在搜索设备前,查询配对设备看需要的设备是否已经是已经存在是很值得的,可以调用getBondedDevices()来做到,该函数会返回一个描述配对设备BluetoothDevice的结果集。例如,可以使用ArrayAdapter查询所有配对设备然后显示所有设备名给用户:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "n" + device.getAddress());
}
};
BluetoothDevice对象中需要用来初始化一个连接唯一需要用到的信息就是MAC地址。

10. 如何实现android蓝牙开发 自动配对连接,并不弹出提示框

我就开始查找怎么关闭这个蓝牙配对提示框,后面还是伟大的android源码帮助了我。
在源码 BluetoothDevice 类中还有两个隐藏方法
cancelBondProcess()和cancelPairingUserInput()
这两个方法一个是取消配对进程一个是取消用户输入
下面是自动配对的代码
Mainfest,xml注册

<receiverandroid:name=".">

<intent-filter>

<actionandroid:name="android.bluetooth.device.action.PAIRING_REQUEST"/>

</intent-filter>

</receiver>

自己在收到广播时处理并将预先输入的密码设置进去


{

StringstrPsw="0";

@Override
publicvoidonReceive(Contextcontext,Intentintent)
{
//TODOAuto-generatedmethodstub
if(intent.getAction().equals(
"android.bluetooth.device.action.PAIRING_REQUEST"))
{
BluetoothDevicebtDevice=intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

//byte[]pinBytes=BluetoothDevice.convertPinToBytes("1234");
//device.setPin(pinBytes);
Log.i("tag11111","ddd");
try
{
ClsUtils.setPin(btDevice.getClass(),btDevice,strPsw);//手机和蓝牙采集器配对
ClsUtils.createBond(btDevice.getClass(),btDevice);
ClsUtils.cancelPairingUserInput(btDevice.getClass(),btDevice);
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}


}
}
<b>/************************************蓝牙配对函数***************/
importjava.lang.reflect.Field;
importjava.lang.reflect.Method;

importandroid.bluetooth.BluetoothDevice;
importandroid.util.Log;
publicclassClsUtils
{

/**
*与设备配对参考源码:platform/packages/apps/Settings.git
*/Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
staticpublicbooleancreateBond(ClassbtClass,BluetoothDevicebtDevice)
throwsException
{
MethodcreateBondMethod=btClass.getMethod("createBond");
BooleanreturnValue=(Boolean)createBondMethod.invoke(btDevice);
returnreturnValue.booleanValue();
}

/**
*与设备解除配对参考源码:platform/packages/apps/Settings.git
*/Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
staticpublicbooleanremoveBond(ClassbtClass,BluetoothDevicebtDevice)
throwsException
{
MethodremoveBondMethod=btClass.getMethod("removeBond");
BooleanreturnValue=(Boolean)removeBondMethod.invoke(btDevice);
returnreturnValue.booleanValue();
}

staticpublicbooleansetPin(ClassbtClass,BluetoothDevicebtDevice,
Stringstr)throwsException
{
try
{
MethodremoveBondMethod=btClass.getDeclaredMethod("setPin",
newClass[]
{byte[].class});
BooleanreturnValue=(Boolean)removeBondMethod.invoke(btDevice,
newObject[]
{str.getBytes()});
Log.e("returnValue",""+returnValue);
}
catch(SecurityExceptione)
{
//thrownewRuntimeException(e.getMessage());
e.printStackTrace();
}
catch(IllegalArgumentExceptione)
{
//thrownewRuntimeException(e.getMessage());
e.printStackTrace();
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returntrue;

}

//取消用户输入
(ClassbtClass,
BluetoothDevicedevice)

throwsException
{
MethodcreateBondMethod=btClass.getMethod("cancelPairingUserInput");
//cancelBondProcess()
BooleanreturnValue=(Boolean)createBondMethod.invoke(device);
returnreturnValue.booleanValue();
}

//取消配对
(ClassbtClass,
BluetoothDevicedevice)

throwsException
{
MethodcreateBondMethod=btClass.getMethod("cancelBondProcess");
BooleanreturnValue=(Boolean)createBondMethod.invoke(device);
returnreturnValue.booleanValue();
}

/**
*
*@paramclsShow
*/
(ClassclsShow)
{
try
{
//取得所有方法
Method[]hideMethod=clsShow.getMethods();
inti=0;
for(;i<hideMethod.length;i++)
{
Log.e("methodname",hideMethod[i].getName()+";andtheiis:"
+i);
}
//取得所有常量
Field[]allFields=clsShow.getFields();
for(i=0;i<allFields.length;i++)
{
Log.e("Fieldname",allFields[i].getName());
}
}
catch(SecurityExceptione)
{
//thrownewRuntimeException(e.getMessage());
e.printStackTrace();
}
catch(IllegalArgumentExceptione)
{
//thrownewRuntimeException(e.getMessage());
e.printStackTrace();
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}</b>
执行时直接使用:
<b>publicstaticbooleanpair(StringstrAddr,StringstrPsw)
{
booleanresult=false;
=BluetoothAdapter
.getDefaultAdapter();

bluetoothAdapter.cancelDiscovery();

if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
}

if(!BluetoothAdapter.checkBluetoothAddress(strAddr))
{//检查蓝牙地址是否有效

Log.d("mylog","devAdneffient!");
}

BluetoothDevicedevice=bluetoothAdapter.getRemoteDevice(strAddr);

if(device.getBondState()!=BluetoothDevice.BOND_BONDED)
{
try
{
Log.d("mylog","NOTBOND_BONDED");
ClsUtils.setPin(device.getClass(),device,strPsw);//手机和蓝牙采集器配对
ClsUtils.createBond(device.getClass(),device);
remoteDevice=device;//配对完毕就把这个设备对象传给全局的remoteDevice
result=true;
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock

Log.d("mylog","setPiNfailed!");
e.printStackTrace();
}//

}
else
{
Log.d("mylog","HASBOND_BONDED");
try
{
ClsUtils.createBond(device.getClass(),device);
ClsUtils.setPin(device.getClass(),device,strPsw);//手机和蓝牙采集器配对
ClsUtils.createBond(device.getClass(),device);
remoteDevice=device;//如果绑定成功,就直接把这个设备对象传给全局的remoteDevice
result=true;
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock
Log.d("mylog","setPiNfailed!");
e.printStackTrace();
}
}
returnresult;
}</b>
热点内容
javarest 发布:2024-09-19 09:28:43 浏览:753
密码子的原料是什么 发布:2024-09-19 09:11:42 浏览:348
半夜编程 发布:2024-09-19 09:11:36 浏览:104
海康威视存储卡质量如何 发布:2024-09-19 08:55:35 浏览:941
python3默认安装路径 发布:2024-09-19 08:50:22 浏览:517
环卫视频拍摄脚本 发布:2024-09-19 08:35:44 浏览:419
sqlserveronlinux 发布:2024-09-19 08:16:54 浏览:257
编程常数 发布:2024-09-19 08:06:36 浏览:953
甘肃高性能边缘计算服务器云空间 发布:2024-09-19 08:06:26 浏览:163
win7家庭版ftp 发布:2024-09-19 07:59:06 浏览:717