简体   繁体   中英

How to control Bluetooth tethering in Android

I have a custom app that needs to use a Bluetooth tethered connection but the "Use for internet access" in the Bluetooth setting for the connection keeps being switched off so I lose the internet connection. As the app only needs to connect every 30 mins or so for a few seconds to update, I can't afford to keep the connection alive (this is a battery powered device)

I've seen apps in the Play Store that allow you to setup auto connect but as this is a custom system, there is no access to the store so I need to include this capability in the app I am developing.

How do I do this from an Android application? Which permissions and system settings do I need to get access to do this from?

try this for Android 2.2

int USBTethering(boolean b) {
    try {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        Log.d(tag, "test enable usb tethering");
        Method[] wmMethods = cm.getClass().getDeclaredMethods();
        String str = "";
        if (b)
            str = "tether";
        else
            str = "untether";
        for (Method method : wmMethods) {
            Log.d("in usb tethering method",method.getName()+"<<nn>>");
            if (method.getName().equals(str)) {
                Log.d(tag, "gg==" + method.getName());
                Log.d("in if", " case matches "+method.getName()+"and str is "+str);
                try {
                    Integer code = (Integer) method.invoke(cm, "usb0");
                //  code = (Integer) method.invoke(cm, "setting TH");
                    Log.d(tag, "code===" + code);
                    return 1;
                } catch (IllegalArgumentException e) {
                    Log.d(tag, "eroor== gg " + e.toString());
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    Log.d(tag, "eroor== gg " + e.toString());
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    Log.d(tag, "eroor== gg " + e.toString());
                    e.printStackTrace();
                }
            }
        }
        return 0;

                   } catch (Exception e) {
        Log.e(tag, "" + e);
        return 0;
    }

}

for Android 4.0 device add following lines

method.setAccessible(true);

before you call

Integer code = (Integer) method.invoke(cm, "usb0");

The other thing is that the interface name (in your case "usb0" is also vendor-specific. The interface name is different on different devices from different manufacturers. Make sure that you've got the correct interface name for the device you are testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM