版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_38184748/article/details/89526686
前言
最近遇到要使用蓝牙的情况,需要使用BluetoothAdapter里的enableBLE方法。
但是这个方法在类中是隐藏的,如下图
就是@SystemApi上方的@hide
上代码
public boolean enableBLE(Context context) {
// 获取BluetoothAdapter的一个实例
BluetoothAdapter mAdapter = getAdapter(context);
if (mAdapter == null)
return false;
try {
// 拿到类
Class ownerClass = Class.forName("android.bluetooth.BluetoothAdapter");
// 拿到类的方法
// 后面的new Class[0]这个指的是参数的类型集合
// 如果有int型参数,那集合里就包含一个int.Class
Method localMethod = ownerClass.getMethod("enableBLE", new Class[0]);
// 反射方法结果
// new Object[0]是对应的参数value
boolean bool = ((Boolean) localMethod.invoke(mAdapter, new Object[0])).booleanValue();
return bool;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return false;
}