如何在Android 8.0(Oreo)中以编程方式打开/关闭wifi热点
我知道如何使用以下方法在android中使用反射来开启/关闭wifi热点。如何在Android 8.0(Oreo)中以编程方式打开/关闭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;
}
但上述方法不适用于Android 8.0(奥利奥)。
当我在Android 8.0中执行上面的方法时,我在logcat中获得了下面的语句。
com.gck.dummy W/WifiManager: com.gck.dummy attempted call to setWifiApEnabled: enabled = true
是否有任何其他的方式,在Android 8.0
开/关热点我终于得到了解决。 Android 8.0,他们提供了公开的api来打开/关闭热点。 WifiManager
下面是代码开启热点
@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");
}
@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());
}
onStarted(WifiManager.LocalOnlyHotspotReservation reservation)
方法,如果热点已开启你打电话close()
方法关闭热点将被称为..使用WifiManager.LocalOnlyHotspotReservation
参考。
更新: 要打开热点,在Location(GPS)
应在设备中启用。否则,它会抛出SecurityException
我有这个错误“java.lang.SecurityException:UID 10103没有位置权限”,虽然我启用设备中的位置并在清单文件中添加权限。你添加的权限是什么? –
@JeanCreuzédesChâtelliers根据文档,应用程序应具有CHANGE_WIFI_STATE和ACCESS_COARSE_LOCATION权限。在打开热点之前,GPS(位置)应该打开。确保上面提到的2个权限被授予。 – Chandrakanth
哎呀,对不起。我忘记激活ACCESS_COARSE_LOCATION权限,尽管我将它添加到清单中。 –
是否要关闭wifi或热点 – MrAppMachine
我想打开/关闭热点...不是wifi ... – Chandrakanth
是否有可能他们删除了这种方式在Android O ?打开wifi热点不是Android SDK的一部分。因此,这种方式使用反射是有点hacky – Rafa