本文来自http://blog.youkuaiyun.com/hellogv/ ,引用必须注明出处!
上次讲解Android的蓝牙基本用法,这次讲得深入些,探讨下蓝牙方面的隐藏API。用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK中给出,那么如何去使用这两项功能呢?本文利用JAVA的反射机制去调用这两项功能对应的函数:createBond和removeBond,具体的发掘和实现步骤如下:
1.使用Git工具下载platform/packages/apps/Settings.git,在Setting源码中查找关于建立配对和解除配对的API,知道这两个API的宿主(BluetoothDevice);
2.使用反射机制对BluetoothDevice枚举其所有方法和常量,看看是否存在:
- static public void printAllInform(Class clsShow) {
- try {
- // 取得所有方法
- Method[] hideMethod = clsShow.getMethods();
- int i = 0;
- for (; i < hideMethod.length; i++) {
- Log.e("method name", hideMethod[i].getName());
- }
- // 取得所有常量
- Field[] allFields = clsShow.getFields();
- for (i = 0; i < allFields.length; i++) {
- Log.e("Field name", allFields[i].getName());
- }
- } catch (SecurityException e) {
- // throw new RuntimeException(e.getMessage());
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- // throw new RuntimeException(e.getMessage());
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
结果如下:
11-29 09:19:12.012: method name(452): cancelBondProcess
11-29 09:19:12.020: method name(452): cancelPairingUserInput
11-29 09:19:12.020: method name(452): createBond
11-29 09:19:12.020: method name(452): createInsecureRfcommSocket
11-29 09:19:12.027: method name(452): createRfcommSocket
11-29 09:19:12.027: method name(452): createRfcommSocketToServiceRecord
11-29 09:19:12.027: method name(452): createScoSocket
11-29 09:19:12.027: method name(452): describeContents
11-29 09:19:12.035: method name(452): equals
11-29 09:19:12.035: method name(452): fetchUuidsWithSdp
11-29 09:19:12.035: method name(452): getAddress
11-29 09:19:12.035: method name(452): getBluetoothClass
11-29 09:19:12.043: method name(452): getBondState
11-29 09:19:12.043: method name(452): getName
11-29 09:19:12.043: method name(452): getServiceChannel
11-29 09:19:12.043: method name(452): getTrustState
11-29 09:19:12.043: method name(452): getUuids
11-29 09:19:12.043: method name(452): hashCode
11-29 09:19:12.043: method name(452): isBluetoothDock
11-29 09:19:12.043: method name(452): removeBond
11-29 09:19:12.043: method name(452): setPairingConfirmation
11-29 09:19:12.043: method name(452): setPasskey
11-29 09:19:12.043: method name(452): setPin
11-29 09:19:12.043: method name(452): setTrust
11-29 09:19:12.043: method name(452): toString
11-29 09:19:12.043: method name(452): writeToParcel
11-29 09:19:12.043: method name(452): convertPinToBytes
11-29 09:19:12.043: method name(452): getClass
11-29 09:19:12.043: method name(452): notify
11-29 09:19:12.043: method name(452): notifyAll
11-29 09:19:12.043: method name(452): wait
11-29 09:19:12.051: method name(452): wait
11-29 09:19:12.051: method name(452): wait
3.如果枚举发现API存在(SDK却隐藏),则自己实现调用方法:
- /**
- * 与设备配对 参考源码:platform/packages/apps/Settings.git
- * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
- */
- static public boolean createBond(Class btClass,BluetoothDevice btDevice) throws Exception {
- Method createBondMethod = btClass.getMethod("createBond");
- Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
- return returnValue.booleanValue();
- }
- /**
- * 与设备解除配对 参考源码:platform/packages/apps/Settings.git
- * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
- */
- static public boolean removeBond(Class btClass,BluetoothDevice btDevice) throws Exception {
- Method removeBondMethod = btClass.getMethod("removeBond");
- Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
- return returnValue.booleanValue();
- }
PS:SDK之所以不给出隐藏的API肯定有其原因,也许是出于安全性或者是后续版本兼容性的考虑,因此不能保证隐藏API能在所有Android平台上很好地运行。。。
本文程序运行效果如下:
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">
- <LinearLayout android:id="@+id/LinearLayout01"
- android:layout_height="wrap_content" android:layout_width="fill_parent">
- <Button android:layout_height="wrap_content" android:id="@+id/btnSearch"
- android:text="Search" android:layout_width="160dip"></Button>
- <Button android:layout_height="wrap_content"
- android:layout_width="160dip" android:text="Show" android:id="@+id/btnShow"></Button>
- </LinearLayout>
- <LinearLayout android:id="@+id/LinearLayout02"
- android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
- <ListView android:id="@+id/ListView01" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- </ListView>
- </LinearLayout>
工具类ClsUtils.java源码如下:
- package com.testReflect;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import android.bluetooth.BluetoothDevice;
- import android.util.Log;
- public class ClsUtils {
- /**
- * 与设备配对 参考源码:platform/packages/apps/Settings.git
- * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
- */
- static public boolean createBond(Class btClass,BluetoothDevice btDevice) throws Exception {
- Method createBondMethod = btClass.getMethod("createBond");
- Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
- return returnValue.booleanValue();
- }
- /**
- * 与设备解除配对 参考源码:platform/packages/apps/Settings.git
- * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
- */
- static public boolean removeBond(Class btClass,BluetoothDevice btDevice) throws Exception {
- Method removeBondMethod = btClass.getMethod("removeBond");
- Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
- return returnValue.booleanValue();
- }
- /**
- *
- * @param clsShow
- */
- static public void printAllInform(Class clsShow) {
- try {
- // 取得所有方法
- Method[] hideMethod = clsShow.getMethods();
- int i = 0;
- for (; i < hideMethod.length; i++) {
- Log.e("method name", hideMethod[i].getName());
- }
- // 取得所有常量
- Field[] allFields = clsShow.getFields();
- for (i = 0; i < allFields.length; i++) {
- Log.e("Field name", allFields[i].getName());
- }
- } catch (SecurityException e) {
- // throw new RuntimeException(e.getMessage());
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- // throw new RuntimeException(e.getMessage());
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
主程序testReflect.java的源码如下:
- package com.testReflect;
- import java.util.ArrayList;
- import java.util.List;
- 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.util.Log;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.ListView;
- import android.widget.Toast;
- public class testReflect extends Activity {
- Button btnSearch, btnShow;
- ListView lvBTDevices;
- ArrayAdapter<String> adtDevices;
- List<String> lstDevices = new ArrayList<String>();
- BluetoothDevice btDevice;
- BluetoothAdapter btAdapt;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- btnSearch = (Button) this.findViewById(R.id.btnSearch);
- btnSearch.setOnClickListener(new ClickEvent());
- btnShow = (Button) this.findViewById(R.id.btnShow);
- btnShow.setOnClickListener(new ClickEvent());
- lvBTDevices = (ListView) this.findViewById(R.id.ListView01);
- adtDevices = new ArrayAdapter<String>(testReflect.this,
- android.R.layout.simple_list_item_1, lstDevices);
- lvBTDevices.setAdapter(adtDevices);
- lvBTDevices.setOnItemClickListener(new ItemClickEvent());
- btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
- if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 开蓝牙
- btAdapt.enable();
- // 注册Receiver来获取蓝牙设备相关的结果
- IntentFilter intent = new IntentFilter();
- intent.addAction(BluetoothDevice.ACTION_FOUND);
- intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
- registerReceiver(searchDevices, intent);
- }
- private BroadcastReceiver searchDevices = new BroadcastReceiver() {
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- Bundle b = intent.getExtras();
- Object[] lstName = b.keySet().toArray();
- // 显示所有收到的消息及其细节
- for (int i = 0; i < lstName.length; i++) {
- String keyName = lstName[i].toString();
- Log.e(keyName, String.valueOf(b.get(keyName)));
- }
- // 搜索设备时,取得设备的MAC地址
- if (BluetoothDevice.ACTION_FOUND.equals(action)) {
- BluetoothDevice device = intent
- .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- if (device.getBondState() == BluetoothDevice.BOND_NONE) {
- String str = "未配对|" + device.getName() + "|" + device.getAddress();
- lstDevices.add(str); // 获取设备名称和mac地址
- adtDevices.notifyDataSetChanged();
- }
- }
- }
- };
- class ItemClickEvent implements AdapterView.OnItemClickListener {
- @Override
- public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
- long arg3) {
- btAdapt.cancelDiscovery();
- String str = lstDevices.get(arg2);
- String[] values = str.split("//|");
- String address=values[2];
- btDevice = btAdapt.getRemoteDevice(address);
- try {
- if(values[0].equals("未配对"))
- {
- Toast.makeText(testReflect.this, "由未配对转为已配对", 500).show();
- ClsUtils.createBond(btDevice.getClass(), btDevice);
- }
- else if(values[0].equals("已配对"))
- {
- Toast.makeText(testReflect.this, "由已配对转为未配对", 500).show();
- ClsUtils.removeBond(btDevice.getClass(), btDevice);
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- /**
- * 按键处理
- * @author GV
- *
- */
- class ClickEvent implements View.OnClickListener {
- @Override
- public void onClick(View v) {
- if (v == btnSearch) {//搜索附近的蓝牙设备
- lstDevices.clear();
- Object[] lstDevice = btAdapt.getBondedDevices().toArray();
- for (int i = 0; i < lstDevice.length; i++) {
- BluetoothDevice device=(BluetoothDevice)lstDevice[i];
- String str = "已配对|" + device.getName() + "|" + device.getAddress();
- lstDevices.add(str); // 获取设备名称和mac地址
- adtDevices.notifyDataSetChanged();
- }
- // 开始搜索
- setTitle("本机蓝牙地址:" + btAdapt.getAddress());
- btAdapt.startDiscovery();
- }
- else if(v==btnShow){//显示BluetoothDevice的所有方法和常量,包括隐藏API
- ClsUtils.printAllInform(btDevice.getClass());
- }
- }
- }
- }
-
46楼
vipclx 2012-06-07 19:41发表 [回复] [引用] [举报]
-
- 大神啊~~~在网上搜了半天发现蓝牙讲解有技术含量的仅此一家,我最近也在弄蓝牙方面,因为初次涉及,好多不懂,能加我QQ指点下迷津吗?感觉不尽,我QQ513644511,谢谢
-
45楼
ahjxly 2012-03-20 14:18发表 [回复] [引用] [举报]
-
- 蓝牙连接时怎么弄的哦?貌似是用createRfcommSocket反射调用呢,还是connect??通过UUID传递是不是不可以??
-
43楼
android_hi 2011-09-28 16:04发表 [回复] [引用] [举报]
-
-
java123yy@163.com
写得真不错,目前我正在解决蓝牙这一块的问题,网上深入研究的,貌似就你这一个了。
所以,楼主,诚心求该蓝牙源码。谢谢啦!
-
42楼
aaaaaaaaaaaaaaaaaaaa 2011-08-15 11:40发表 [回复] [引用] [举报]
-
-
谁知道android蓝牙自动配对怎么实现,谢谢啊,我一直在找这个的实现代码,但是很不幸,到现在找了一个星期 了,依然没有解决方案,我的qq1149598411
-
Re:
咪当俺系噜噜 2011-08-16 12:20发表 [回复] [引用] [举报]
-
-
回复haojunming:我也尝试过自动配对,但这个不是Framework层的,更底层来实现
-
Re:
aaaaaaaaaaaaaaaaaaaa 2011-08-23 18:10发表 [回复] [引用] [举报]
-
- 回复hellogv:或者你能不能写一篇文章就是专门关于android蓝牙在framework层不能实现自动配对的文章?
-
Re:
aaaaaaaaaaaaaaaaaaaa 2011-08-23 17:42发表 [回复] [引用] [举报]
-
-
回复hellogv:我实现了自动配对,可是配对成功后依然会弹出那个配对框, 只是很快就又消失了,我分析是,我自己对那个配对的广播进行了监听,在onReceive方法里面手动输入配对码,可是系统也对这个进行监听,所以都对此作出了处理,这样才造成这个结局,不知道有没有什么好的解决方案。我们公司的项目经理催我很厉害了,帮帮忙。如果真的不能在framework层实现自动配对的话,能不能告诉我为什么啊,谢谢
-
Re:
咪当俺系噜噜 2011-08-24 18:37发表 [回复] [引用] [举报]
-
-
回复haojunming:因为framework也是直接调用底层蓝牙驱动来实现的,这里framework也是无济于事
-
Re:
aaaaaaaaaaaaaaaaaaaa 2011-08-25 14:24发表 [回复] [引用] [举报]
-
- 回复hellogv:我的一个设想是android当中的设置配对信息应该是保存起来的,那么我手动的把配对信息写进去行吗?
-
Re:
aaaaaaaaaaaaaaaaaaaa 2011-08-25 14:22发表 [回复] [引用] [举报]
-
- 回复hellogv:问您一件事情,android中 Setting里面的那些设置信息都保存在哪里了?
-
-
-
-
-
41楼
muyiangel7 2011-08-15 09:28发表 [回复] [引用] [举报]
-
-
最近在做android蓝牙这方面,想请问楼主怎样才能消除掉蓝牙匹配的弹出框(就是不用用户点击“是”这个按钮就能完成匹配,对用户要隐藏)?跪求指导!
-
Re:
aaaaaaaaaaaaaaaaaaaa 2011-08-24 08:34发表 [回复] [引用] [举报]
-
- 回复muyiangel7:我也在做这个蓝牙自动配对,不知道你有什么解决方案吗
-
-
40楼
aaaaaaaaaaaaaaaaaaaa 2011-08-12 10:03发表 [回复] [引用] [举报]
-
- 大哥,问一下,android蓝牙自动配对该怎么办啊,我自己从网上找了好多这样的东西可是都不合适,能不能给写一个可用的实例代码,谢谢啊
-
39楼
wuchuanpingstone 2011-08-10 11:14发表 [回复] [引用] [举报]
-
-
String[] values = str.split("//|");
String address=values[2];
应该为:
String[] values = str.split("\|");
String address=values[1];
数组下标从0开始的
-
38楼
aaaaaaaaaaaaaaaaaaaa 2011-08-01 11:49发表 [回复] [引用] [举报]
-
- :蓝牙本身就支持1对7的链接但是我需要有uuid才可以, 现在我是找不到那么多的uuid,您知道它是怎么取得的吗?或者说它是怎么生成的,有相应的代码吗?能不能给发一份,谢谢啊,我的手机号18701427983,qq1149598411
-
37楼
aaaaaaaaaaaaaaaaaaaa 2011-08-01 11:47发表 [回复] [引用] [举报]
-
-
可是我的那个是串口连接,需要对应的uuid,我不知道该怎么设置,您能不能给提供几个对应的uuid,我自己从网上找了两个,但是还需要五个,蓝牙串口服务 SerialPortServiceClass_UUID: TGUID = '{00001101-0000-1000-8000-00805F9B34FB}';
LANAccessUsingPPPServiceClass_UUID: TGUID = '{00001102-0000-1000-8000-00805F9B34FB}';
-
36楼
aaaaaaaaaaaaaaaaaaaa 2011-08-01 10:59发表 [回复] [引用] [举报]
-
- 大哥,我现在在做蓝牙的一对多连接,如果我要是手机作为服务器,同时接收几个蓝牙设备,那么这个uuid该怎么配置,谢谢啊
-
35楼
lighthearts 2011-07-07 20:35发表 [回复] [引用] [举报]
-
-
楼主,我有个问题,怎样判断远端的bluetoothdevice是手机还是pc??我找了很多方法都没有比较完善的,我想到的就是根据设备上面的服务来判断了
-
Re:
yuanbieli 2011-08-19 11:38发表 [回复] [引用] [举报]
-
-
回复lighthearts:这个android本身应该是已经实现了。
看settings的源码,android已经能区分搜索到的设备是PC还是手机。
参考:com.android.settings.bluetooth.CachedBluetoothDevice.java
getBtClassDrawable()方法中的如下代码,
switch (mBtClass.getMajorDeviceClass()) {
case BluetoothClass.Device.Major.COMPUTER:
return R.drawable.ic_bt_laptop;
case BluetoothClass.Device.Major.PHONE:
return R.drawable.ic_bt_cellphone;}
已经实现根据设备不同选用不同图标。
核心类用到BluetoothClass.java
供参考~
-
-
33楼
sunrongrong 2011-06-07 13:51发表 [回复] [引用] [举报]
-
- 楼主能否获取到蓝牙的信号强度值啊?
-
32楼
L_e_o_n 2011-05-08 00:40发表 [回复] [引用] [举报]
-
-
请问Android蓝牙可以实现不进行自动配对么?
原因是我要利用串口连接一个没有操作系统的蓝牙发射器,当我手机搜索到这个发射器之后,手机提示我要进行配对操作,但是我发射器没有操作系统,是不能配对的,请问您有什么方法能够避免这个配对的过程么?[e03]
-
31楼
longlong870125 2011-04-21 10:40发表 [回复] [引用] [举报]
-
- 楼主你好,怎么http://www.pudn.com/downloads305/sourcecode/comm/android/detail1359043.html里面的源码下载不了的呢,麻烦发份到本人邮箱,343827585@qq.com,急需,谢谢。
-
29楼
edifier_jcc 2011-04-15 06:16发表 [回复] [引用] [举报]
-
- 楼主,程序非常不错,简洁,而且没有用到ListActivity这个鸡“类”,感觉蛮好的!顶一下~对我的帮助非常大,但是我发现你的代码里面有bug,按那个show按钮的话会强行退出程序的!求解~~谢谢楼主!
-
28楼
xiaoqiangvs007 2011-04-12 12:51发表 [回复] [引用] [举报]
-
- 我系中山噶,目前在珠海搞android,有空多多向楼主学习QQ:191972323
-
26楼
gaocheng1988 2011-03-07 09:58发表 [回复] [引用] [举报]
-
- [e01]
-
25楼
wutongyu344 2011-03-02 21:53发表 [回复] [引用] [举报]
-
- [e01][e01][e01][e01][e01]
-
24楼
yanghuaixi 2011-02-21 16:42发表 [回复] [引用] [举报]
-
- [e01][e01][e01]
-
20楼
spiderppp 2011-01-11 15:55发表 [回复] [引用] [举报]
-
-
确实不错!有个问题文下楼主Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
里面有个 private final BluetoothDevice mDevice;
if (!mDevice.createBond()) {
mLocalManager.showError(mDevice, R.string.bluetooth_error_title,
R.string.bluetooth_pairing_error_message);
return;
}
BluetoothDevice 的源码那里下。。我下载的platform/packages/apps/Bluetooth.git里面没有,还请楼主指教!
-
18楼
yanghuaixi 2010-12-29 14:23发表 [回复] [引用] [举报]
-
- [e01]
-
17楼
raindrophust 2010-12-09 16:25发表 [回复] [引用] [举报]
-
- 呵呵,我是把源码整个拉下来,找到这个配对函数的。[e01]
-
14楼
lz408682690 2010-11-30 15:19发表 [回复] [引用] [举报]
-
- [e01]
-
13楼
ggggnuirgw 2010-11-30 14:08发表 [回复] [引用] [举报]
-
- 动画时间太快了,以后的可能慢点不[e06]
-
11楼
QQ1428613557 2010-11-30 11:02发表 [回复] [引用] [举报]
-
- [e01]
-
10楼
wangquan123456789 2010-11-30 09:44发表 [回复] [引用] [举报]
-
- 偶像啊[e03]
-
7楼
fanwander0711 2010-11-29 13:36发表 [回复] [引用] [举报]
-
- 继续跟进。。。。
-
3楼
qwe285735942 2010-11-29 10:27发表 [回复] [引用] [举报]
-
- 被逼来顶,不过不错