首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否从代码启动/停止内置Wi-Fi / USB tethering?

是否从代码启动/停止内置Wi-Fi / USB tethering?
EN

Stack Overflow用户
提问于 2010-08-09 06:12:22
回答 4查看 11.4K关注 0票数 7

如何从我的应用程序中启动或停止Android 2.2中的内置tethering?

EN

回答 4

Stack Overflow用户

发布于 2013-02-07 23:34:45

ConnectivityManager中有一个非公共的Tethering API。如上所示,您可以使用反射来访问它。我在很多安卓2.2手机上试用过,所有的手机都能用(我的HTC开启了网络连接,但状态栏上没有显示出来……所以从另一端查看)。下面是一些粗略的代码,这些代码发出调试内容并打开usb0上的tethering。

代码语言:javascript
复制
ConnectivityManager cman = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

Method[] methods = cman.getClass().getDeclaredMethods();
for (Method method : methods) {
    if (method.getName().equals("getTetherableIfaces")) {
        try {
            String[] ifaces = (String[]) method.invoke(cman);
            for (String iface : ifaces) {
                Log.d("TETHER", "Tether available on " + iface);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (method.getName().equals("isTetheringSupported")) {
        try {
            boolean supported = (Boolean) method.invoke(cman);
            Log.d("TETHER", "Tether is supported: " + (supported ? "yes" : "no"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (method.getName().equals("tether")) {
        Log.d("TETHER", "Starting tether usb0");
        try {
            int result = (Integer) method.invoke(cman, "usb0");
            Log.d("TETHER", "Tether usb0 result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

请注意:此代码需要以下权限才能工作:

代码语言:javascript
复制
android.permission.ACCESS_NETWORK_STATE
android.permission.CHANGE_NETWORK_STATE
票数 8
EN

Stack Overflow用户

发布于 2012-11-28 14:17:59

我回答了这个问题,here。简而言之,it is possible,代码如下:

代码语言:javascript
复制
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;
        }
    }
}

您的应用程序应具有以下权限:

android.permission.CHANGE_WIFI_STATE

票数 3
EN

Stack Overflow用户

发布于 2010-08-09 06:22:59

Android SDK中没有用于管理系留的公共APIs -抱歉!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3436280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档