源:http://www.cnblogs.com/xiaochao1234/p/3793172.html

上次讲解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. Android开发之探秘蓝牙隐藏API

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

  3. 探秘蓝牙隐藏API

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

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

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

  5. 安卓开发 利用百度识图api进行物体识别

    前文 之前的随笔中,已经通过相机或相册获取到了我们想要的图片,接下来进行识图api的配置工作.我使用的是百度的api,利用python获取信息,并在MainActivity中进行调用来输出信息. 一. ...

  6. 安卓开发 利用百度识图api进行物体识别(java版)

    之前的随笔中,已经实现了python版本调用api接口,之所以使用python是因为python比java要简洁. 但是我发现在使用过程中,chaquopy插件会弹出底部toast显示"un ...

  7. Kotlin 语言高级安卓开发入门

    过去一年,使用 Kotlin 来为安卓开发的人越来越多.即使那些现在还没有使用这个语言的开发者,也会对这个语言的精髓产生共鸣,它给现在 Java 开发增加了简单并且强大的范式.Jake Wharton ...

  8. 安卓开发笔记——TabHost组件(二)(实现底部菜单导航)

    上面文章<安卓开发复习笔记——TabHost组件(一)(实现底部菜单导航)>中提到了利用自定义View(ImageView+TextView)来设置一个底部菜单的样式 这边再补充一种更为灵 ...

  9. 安卓开发开发规范手册V1.0

    安卓开发开发规范手册V1.0 之前发布过一份Web安全开发规范手册V1.0,看到收藏文章的读者挺多,发现整理这些文档还挺有意义. 最近周末抽了些时间把之前收集关于安卓安全开发的资料也整理了一下,整理出 ...

随机推荐

  1. 如何通过Maven的Jetty插件运行Web工程

    首先建议使用jetty9,因为据官方文档显示,Jetty 7 and Jetty 8 are now EOL (End of Life),如下.但是由于项目使用的版本一般都比较低,这里以jetty8为 ...

  2. netsh命令之ip设置

    批处理.VBS实现自动设置IP.默认网关.DNS.WINS.IE代理的代码,需要的朋友可以参考下 因为公司有同事负责大连.沈阳两个城市,经常在两地来回走动,到每个城市后,都要自己手动更改相应的网络配置 ...

  3. windows7所有版本

    windows7所有版本迅雷地址下载集合(含32位和64位) Windows7 SP1旗舰版 32位官方原版下载: ed2k://|file|/cn_windows_7_ultimate_with_s ...

  4. linex下部署发布web项目

    准备工作:通过Xmanager远程连接linux系统,下载对应的jdk和tomcat. 1.通过Xmanager远程连接linux系统,下载地址请自己网上搜索吧. 2.下载jdk (这里为jdk-7u ...

  5. json 数组 对象 xml 之间转换(待补充)

    json 数组  xml 对象   之间转换(待补充) 1 把对象的类型或者数组转换成字符串类型(或者更确切的说是json类型的). 此处参考链接http://www.jb51.net/article ...

  6. hdu_3518_Boring counting(后缀数组)

    题目链接:hdu_3518_Boring counting 题意: 给你一个字符串,让你找不重叠且出现大于1次以上的字串个数 题解: 后缀数组height数组的应用,我们枚举字串的长度,然后将heig ...

  7. Educational Codeforces Round 15_D. Road to Post Office

    D. Road to Post Office time limit per test 1 second memory limit per test 256 megabytes input standa ...

  8. 网络请求 get post

    1.新建一个网络请求工具类,负责整个项目中所有的Http网络请求 提示:同步请求会卡住线程,发送网络请求应该使用异步请求(这意味着类方法不能有返回值) 2.工具类的实现 YYHttpTool.h文件 ...

  9. 修改NavigationBar样式

    iOS Tip: Change Status Bar Icon & Text Colors When iOS 7 was introduced Apple allowed your appli ...

  10. 【伪一周小结(没错我一周就做了这么点微小的工作)】HDOJ-1241 Oil Deposits 初次AC粗糙版对比代码框架重构版

    2016 11月最后一周 这一周复习了一下目前大概了解的唯一算法--深度优先搜索算法(DFS).关于各种细节的处理还是极为不熟练,根据题意判断是否还原标记也无法轻松得出结论.不得不说,距离一个准ACM ...