0

我正在尝试从应用程序在 android nexus 5 4.4.4 上启用蓝牙网络共享。

有没有人有这方面的工作代码?我已经看到一些使用“android.bluetooth.BluetoothPan”类的例子,但我无法让它工作。

通过示例,我在 logcat 中收到以下错误:

java.lang.reflect.InvocationTargetException Caused by: java.lang.NullPointerException at android.bluetooth.BluetoothPan.isTetheringOn(BluetoothPan.java:346)

谢谢指教。

更新:这里有更多细节。我尝试获取当前的网络共享状态。

onCreate 方法:

private boolean btEnabled = false;

BluetoothAdapter mBluetoothAdapter = null;
Class<?> classBluetoothPan = null;
Constructor<?> BTPanCtor = null;
Object BTSrvInstance = null;
Class<?> noparams[] = {};
Method mIsBTTetheringOn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    try {
        RetrieveWeather();
    } catch (IOException e) {
        e.printStackTrace();
    }
    CheckBluetoothState();


    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();
    }


    boolean test = IsBluetoothTetherEnabled();
    if (test){
        Log.d("Tethering", "Bluetooth Tethering is On");
    } else {
        Log.d("Tethering", "Bluetooth Tethering is Off");
    }
}



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;
}

错误发生在以下行: return (Boolean) mIsBTTetheringOn.invoke(BTSrvInstance, (Object []) noparams);

此致

4

0 回答 0