从代码启动/停止内置Wi-Fi/USB网络共享?

Isa*_*ler 7 android wifi android-2.2-froyo

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

小智 7

有一个非公开的Tethering API ConnectivityManager.如上所示,您可以使用反射来访问它.我在许多Android 2.2手机上试过这个,它适用于所有这些(我的HTC打开了网络共享,但没有在状态栏中显示...,所以从另一端检查).下面是一些粗略的代码,它们发出调试内容并打开usb0上的tethering.

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

android.permission.ACCESS_NETWORK_STATE
android.permission.CHANGE_NETWORK_STATE
Run Code Online (Sandbox Code Playgroud)


Com*_*are 0

Android SDK 中没有用于管理网络共享的公共 API - 抱歉!