Android打开热点前,获取上次设置热点的ssid和密码
问题描述:
因为现在在做个小功能,遇到这个问题就头大。下面这段是通过反射打开热点
try {
Method method = wifiManager.getClass().getMethod(
"setWifiApEnabled", WifiConfiguration.class, boolean.class);
method.invoke(wifiManager, apconfig, true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
这种打开方式是需要WifiConfiguration的,也就是基本属性包括ssid和密码等。wifimanager也没有方法能获取到这些
但是我只是做个开关,问各位哥。有什么能获取上次设置热点的信息,或者有不需要基本属性就能打开热点的方法?
答
可以通过反射startTethering这个方法打开热点,之前的博客找不到了,前段时间才用过,现在忘的差不多了,好像有些权限和这个依赖
implementation 'com.google.dexmaker:dexmaker:1.2'
下面是使用示例。
/**
* 打开WiFi热点
* @param context
*/
public static void startTethering(Context context) {
//1、环境属性记录
String property = System.getProperty("dexmaker.dexcache");
//2、设置新的属性
System.setProperty("dexmaker.dexcache", context.getCacheDir().getPath());
//3、反射操作打开热点
ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
try {
Class classOnStartTetheringCallback = Class.forName("android.net.ConnectivityManager$OnStartTetheringCallback");
Method startTethering = connectivityManager.getClass().getDeclaredMethod("startTethering", int.class, boolean.class, classOnStartTetheringCallback);
Object proxy = ProxyBuilder.forClass(classOnStartTetheringCallback).handler(new InvocationHandler() {
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
return null;
}
}).build();
startTethering.invoke(connectivityManager, 0, false, proxy);
} catch (Exception e) {
e.printStackTrace();
}
//4、恢复环境属性
if (property != null) {
System.setProperty("dexmaker.dexcache", property);
}
}