有什么方法可以找出在Android 2.3(2.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) {
}
}