上次讲解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:id="@+id/btnSearch"
            android:layout_width="160dip"
            android:layout_height="wrap_content"
            android:text="Search">
        </Button>
        <Button
            android:id="@+id/btnShow"
            android:layout_height="wrap_content"
            android:layout_width="160dip"
            android:text="Show"
        </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());
            }
 
        }
 
    }
 
}

探秘蓝牙隐藏API的更多相关文章

  1. 安卓开发之探秘蓝牙隐藏API

    上次讲解Android的蓝牙基本用法,这次讲得深入些,探讨下蓝牙方面的隐藏API.用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在S ...

  2. 安卓开发之探秘蓝牙隐藏API(转)

    源:http://www.cnblogs.com/xiaochao1234/p/3793172.html 上次讲解Android的蓝牙基本用法,这次讲得深入些,探讨下蓝牙方面的隐藏API.用过Andr ...

  3. Android开发之探秘蓝牙隐藏API

    这次讲得深入些,探讨下蓝牙方面的隐藏API.用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK中给出,那么如何去使用这两项功能呢 ...

  4. Android应用开发中如何使用隐藏API(转)

    一开始需要说明的是,Google之所以要将一些API隐藏(指加上@hide标记的public类.方法或常量)是有原因的.其中很大的原因就是Android系统本身还在不断的进化发展中.从1.0.1.1到 ...

  5. android 隐藏API 在源码下编译报错cannot find symbol symbol

    应该是我对android 不熟悉的缘故,今天使用源码编译了一个调用了隐藏api的应用程序始终报错: cannot find symbol symbol  : class IPackageInstall ...

  6. 自行修改android.jar使其包含隐藏api

    1) 从指定版本的rom内获取到framework.jar 2) 解压framework.jar和android sdk内的android.jar 3) 将framework.jar解出来的东西拷到a ...

  7. Android中使用隐藏API(大量图解)

    Android SDK的很多API是隐藏的,我无法直接使用.但是我们通过编译Android系统源码可以得到完整的API. 编译Android系统源码后可以在out\target\common\obj\ ...

  8. 蓝牙中文API文档

    蓝牙是一种低成本.短距离的无线通信技术.对于那些希望创建个人局域网(PANs)的人们来说,蓝牙技术已经越来越流行了.每个个人局域网都在独立设备的周围被动态地创建,并且为蜂窝式电话和PDA等设备提供了自 ...

  9. Android中的隐藏API和Internal包的使用之获取应用电量排行

    今天老大安排一个任务叫我获取手机中应用耗电排行(时间是前天晚上7点到第二天早上10点),所以在网上各种搜索,没想到这种资料还是很多的,发现了一个主要的类:PowerProfile,但是可以的是,这个类 ...

随机推荐

  1. extjs用iframe的问题

    项目中用extjs做前提系统的界面是左边用树做目录 右边用tabpanel做内容展示点击树节点的时候 在tabpanel添加新的tab JScript code var newTab = center ...

  2. Registering DLL and ActiveX controls from code

    http://delphi.about.com/od/windowsshellapi/l/aa040803a.htm How to register (and unregister) OLE cont ...

  3. Altium Protel PCB Layer

    The layers themselves are grouped by their functional types: Signal Layers – Top Layer, Bottom Layer ...

  4. Jetty开发指导:WebSocket介绍

    WebSocket是一个新的基于HTTP的双向通讯的协议. 它是基于低级别的框架协议.使用UTF-8 TEXT或者BINARY格式传递信息. 在WebSocket中的单个信息能够是不论什么长度(然而底 ...

  5. vagrant多节点配置

    1.vagrantfile的配置 Vagrant.configure("2") do |config| config.vm.box = "xinjieLinux" ...

  6. OpenERP实施记录(11):入库处理

    本文是<OpenERP实施记录>系列文章的一部分. 在前面的文章中,业务部门接到沃尔玛3台联想Y400N笔记本电脑的订单,采购部门完成了补货处理.因为该产品的“最少库存规则”里面定义了“最 ...

  7. Android学习之Http使用Post方式进行数据提交(普通数据和Json数据)

    转自:http://blog.csdn.net/wulianghuan/article/details/8626551 我们知道通过Get方式提交的数据是作为Url地址的一部分进行提交,而且对字节数的 ...

  8. 仿LOL项目开发第三天

    仿LOL项目开发第二天 by草帽 昨个我们已经实现了下载功能,但是发现没有,下载的包是压缩的,没有解压开,那么Unity是识别不了的. 所以今个我们来讲讲如何实现解压文件. 还记得吗,我们在Downl ...

  9. HTML:图片和视频标签的使用

    介绍:在html网页中,图片和视频是基本的元素,在网页中插入图片和视频有自己的标签,分别是img.embed,来源都是使用src来链接. 插入图片: <img src="图片的来源&q ...

  10. Android Studio 打印调试信息

    转自:https://www.2cto.com/kf/201611/569468.html 之前开发单片机软件还是上位机都习惯使用printf(),相信很多很会有和我一样的习惯.开始学习安卓了,当然也 ...