在Android上以编程方式启用/禁用USB或Wifi网络共享

在Android上以编程方式启用/禁用USB或Wifi网络共享

问题描述:

是否可以通过编程方式在Android手机上启用或禁用网络共享(USB或wifi)?也许是Android SDK或NDK中的API或任何甚至非UI命令都可以做到这一点.

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.

谢谢.

是可能的,并且没有根访问权限,我在应用程序中使用了以下代码:

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

android.permission.CHANGE_WIFI_STATE