Android Widget启用蓝牙Tethering

时间:2014-09-21 19:27:01

标签: android bluetooth tethering

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

有没有人有这方面的工作代码?我看过一些使用" android.bluetooth.BluetoothPan"的例子。对此类,但我无法使其正常工作。

使用expamples我在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);

祝你好运

0 个答案:

没有答案