有没有办法找到在Android 2.3+(2.3 +之后的任何版本)中以编程方式启用或禁用蓝牙网络共享?
我不是要求启用/禁用它,而只是要知道它当前是否已启用。
答案 0 :(得分:3)
事实证明,BluetoothPan(个人区域网络)是网络共享的关键字。我对API文档和Android源代码进行了仔细研究,但评论中的简短示例具有误导性。这张海报提供了一个例子,但最初我遇到了麻烦:
Android BluetoothPAN to create TCP/IP network between Android device and Windows7 PC
我尝试了各种其他方法,包括检查BT设备的IP地址。但是,不存在蓝牙网络设备,因此无需检查IP
Detect USB tethering on android
返回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) {
}
}