我知道如何使用下面的方法在android中使用反射打开/关闭wifi热点。
private static boolean changeWifiHotspotState(Context context,boolean enable) {
try {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Method method = manager.getClass().getDeclaredMethod("setWifiApEnabled", WifiConfiguration.class,
Boolean.TYPE);
method.setAccessible(true);
WifiConfiguration configuration = enable ? getWifiApConfiguration(manager) : null;
boolean isSuccess = (Boolean) method.invoke(manager, configuration, enable);
return isSuccess;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
,但上面的方法不适用于Android8.0(奥利奥).
当我在Android8.0中执行上述方法时,我在logcat中得到以下语句。
com.gck.dummy W/WifiManager: com.gck.dummy attempted call to setWifiApEnabled: enabled = true
在Android8.0上还有其他方式来打开/关闭hotspot吗?
发布于 2017-09-01 08:56:09
我终于找到解决办法了。Android8.0,他们提供了公共api来打开/关闭热点。WifiManager
下面的是打开hotspot的代码
private WifiManager.LocalOnlyHotspotReservation mReservation;
@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOnHotspot() {
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
@Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
Log.d(TAG, "Wifi Hotspot is on now");
mReservation = reservation;
}
@Override
public void onStopped() {
super.onStopped();
Log.d(TAG, "onStopped: ");
}
@Override
public void onFailed(int reason) {
super.onFailed(reason);
Log.d(TAG, "onFailed: ");
}
}, new Handler());
}
private void turnOffHotspot() {
if (mReservation != null) {
mReservation.close();
}
}
如果热点打开,将调用onStarted(WifiManager.LocalOnlyHotspotReservation reservation)
方法。使用WifiManager.LocalOnlyHotspotReservation
引用,您可以调用close()
方法来关闭hotspot。
注意:打开热点,Location(GPS)
应该在设备中启用。否则,它将抛出SecurityException
https://stackoverflow.com/questions/45984345
复制相似问题