20

Is there a way to enable or disable tethering (USB or wifi) on an android phone programmatically? Perhaps an API in android SDK or NDK or any even non-UI command to do that.

Thanks in advance.

Gaurav Khurana
  • 201
  • 1
  • 2
  • 3
  • 1
    for usb tethering, see : http://stackoverflow.com/questions/7509924/detect-usb-tethering-on-android/7830747#7830747 for wifi thethering, see: http://stackoverflow.com/questions/3023226/android-2-2-wifi-hotspot-api – byndhorizon Oct 20 '11 at 03:25
  • please check this link https://github.com/abhinay100/wifi-tethering you will get the complete code for wifi tethering which works perfectly –  Mar 17 '16 at 07:54

2 Answers2

11

It is possible and without root access, I use the below code snipped in my apps:

private void setWifiTetheringEnabled(boolean enable) {
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

    Method[] methods = wifiManager.getClass().getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().equals("setWifiApEnabled")) {
            try {
                method.invoke(wifiManager, null, enable);
            } catch (Exception ex) {
            }
            break;
        }
    }
}

Your app should have the following permission:

android.permission.CHANGE_WIFI_STATE

iTech
  • 18,192
  • 4
  • 57
  • 80
  • I get "Failed to start soft AP with a running supplicant" message in logs when trying this on nexus s, stock 4.1. – DixieFlatline Mar 07 '13 at 17:17
  • See the discussion [here](https://code.google.com/p/android/issues/detail?id=1124), it seems to be a reported problem – iTech Mar 07 '13 at 17:55
  • Note that this does not work on Lollipop devices (tested up to 5.1.1), you need to have root access. You will get an InvocationTargetException because application does not have system permission: android.permission.CONNECTIVITY_INTERNAL – vman Nov 03 '15 at 17:35
  • This DO work on 6.0.1 w/o root on a Oneplue One. I at least don't think it is ROM specific, tough not verified. – Victor Häggqvist Feb 19 '16 at 15:16
10

Take a look at this question.

Basically there are no public API's to do it. Take a look at the settings app to see how internal apps do it though. Might have some luck with that:

https://github.com/android/platform_packages_apps_settings/blob/master/src/com/android/settings/TetherSettings.java

Community
  • 1
  • 1
matto1990
  • 3,766
  • 2
  • 27
  • 32
  • 4
    Internal apps can execute setUsbTethering(true); cause they have access to MANAGE_USB permission. It is irrelevant to standart developers. – JaLoveAst1k Jul 30 '14 at 14:08