如何在Android中以编程方式检查蓝牙网络共享状态

有没有办法找到Android 2.3+(2.3+之后的任何版本)以编程方式启用或禁用蓝牙网络共享?

我不是要求启用/禁用它,而只是要知道它当前是否已启用。

事实certificate,BluetoothPan(个人区域网络)是网络共享的关键字。 我仔细研究了API文档和Android源代码,但是评论中的简短示例都是误导性的。 这张海报提供了一个例子,但我最初遇到了麻烦:
Android BluetoothPAN在Android设备和Windows7 PC之间创建TCP / IP网络

我尝试了各种其他方法,包括检查BT设备的IP地址。 但是,不存在蓝牙网络设备,因此无需检查IP。
在android上检测USB网络共享

回到BluetoothPan代码……第一个线程中的示例是不完整的(没有ServiceListener实现)。 我尝试了一个标准的但isTetheringOn代理调用失败了。 关键的一点是onServiceConnected()回调需要至少一行代码或者编译器将其优化掉。 它也不应像大多数其他示例那样断开代理。 这是工作代码:

BluetoothAdapter mBluetoothAdapter = null; Class classBluetoothPan = null; Constructor BTPanCtor = null; Object BTSrvInstance = null; Class noparams[] = {}; Method mIsBTTetheringOn; @Override public void onCreate() { Context MyContext = getApplicationContext(); mBluetoothAdapter = getBTAdapter(); try { classBluetoothPan = Class.forName("android.bluetooth.BluetoothPan"); mIsBTTetheringOn = classBluetoothPan.getDeclaredMethod("isTetheringOn", noparams); BTPanCtor = classBluetoothPan.getDeclaredConstructor(Context.class, BluetoothProfile.ServiceListener.class); BTPanCtor.setAccessible(true); BTSrvInstance = BTPanCtor.newInstance(MyContext, new BTPanServiceListener(MyContext)); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } private BluetoothAdapter getBTAdapter() { if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) return BluetoothAdapter.getDefaultAdapter(); else { BluetoothManager bm = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); return bm.getAdapter(); } } // Check whether Bluetooth tethering is enabled. private boolean IsBluetoothTetherEnabled() { try { if(mBluetoothAdapter != null) { return (Boolean) mIsBTTetheringOn.invoke(BTSrvInstance, (Object []) noparams); } } catch (Exception e) { e.printStackTrace(); } return false; } public class BTPanServiceListener implements BluetoothProfile.ServiceListener { private final Context context; public BTPanServiceListener(final Context context) { this.context = context; } @Override public void onServiceConnected(final int profile, final BluetoothProfile proxy) { //Some code must be here or the compiler will optimize away this callback. Log.i("MyApp", "BTPan proxy connected"); } @Override public void onServiceDisconnected(final int profile) { } }