如何从我的应用程序中启动或停止Android 2.2中内置的网络共享功能?
如何从我的应用程序中启动或停止Android 2.2中内置的网络共享功能?
在ConnectivityManager
中存在一个非公开的共享网络API。如上所示,您可以使用反射来访问它。我在多个Android 2.2手机上尝试过,并且在所有手机上都可以正常工作(我的HTC打开了共享网络但不会在状态栏中显示...,因此请从另一端进行检查)。下面是一些粗略的代码,它会发出调试信息并在usb0上打开共享网络。
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();
}
}
}
android.permission.ACCESS_NETWORK_STATE
android.permission.CHANGE_NETWORK_STATE
我在这里回答了这个问题。简而言之,是可以的,以下是代码:
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;
}
}
}
您的应用程序应具备以下权限:
(注:此权限允许您的应用程序更改设备的 Wi-Fi 连接状态。)android.permission.CHANGE_WIFI_STATE
setWifiApDisabled
方法吗?还是可以使用method.invoke(wifiManager, null, disable)
? - SubliemeSiemWifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// TODO Auto-generated method stub
WifiConfiguration wifi_configuration = null;
wifiManager.setWifiEnabled(false);
try
{
//USE REFLECTION TO GET METHOD "SetWifiAPEnabled"
Method method=wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method.invoke(wifiManager, wifi_configuration, true);
}
catch (NoSuchMethodException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
很抱歉,在Android SDK中没有公共API用于管理网络共享。