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

3

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

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

1个回答

4
原来 BluetoothPan (个人局域网) 是连接共享网络的关键词。我仔细研究了 API 文档和 Android 源代码,但注释中简短的示例却是误导性的。这位发帖者提供了一个示例,但一开始我遇到了问题:
Android BluetoothPAN to create TCP/IP network between Android device and Windows7 PC
我尝试了各种其他方法,包括检查 BT 设备的 IP 地址。然而没有 Bluetooth 网络设备存在,因此也没有 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) {
    }
}

1
尝试使用相同的代码,但在调用isTetheringOn时出现了调用目标异常。已注册蓝牙和蓝牙管理员权限。 - MGK
1
我也无法工作... 没有异常,但值仍为false。 - Tobliug
不起作用 :-( 无异常,但值保持为 false - Maveňツ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接