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

时间:2022-04-17 16:08:43

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.

有没有办法以编程方式在Android手机上启用或禁用网络共享(USB或wifi)?也许是Android SDK或NDK中的API或任何甚至非UI命令来做到这一点。

Thanks in advance.

提前致谢。

2 个解决方案

#1


11  

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

这是可能的,没有root访问权限,我使用以下代码剪切在我的应用程序中:

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

#2


8  

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:

基本上没有公共API可以做到这一点。看看设置应用程序,看看内部应用程序如何做到这一点。可能有点运气:

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

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

#1


11  

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

这是可能的,没有root访问权限,我使用以下代码剪切在我的应用程序中:

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

#2


8  

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:

基本上没有公共API可以做到这一点。看看设置应用程序,看看内部应用程序如何做到这一点。可能有点运气:

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

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