问题描述
我知道如何使用以下方法在 android 中使用反射打开/关闭 wifi 热点.
I know how to turn on/off wifi hot spot using reflection in android using below method.
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(Oreo).
当我在 Android 8.0 中执行上述方法时,我在 logcat 中得到以下语句.
But the above method is not working Android 8.0(Oreo).
When I execute above method in Android 8.0, I am getting below statement in logcat.
com.gck.dummy W/WifiManager: com.gck.dummy attempted call to setWifiApEnabled: enabled = true
有没有其他方法可以在 android 8.0 上打开/关闭热点
Is there any other way to on/off hotspot on android 8.0
推荐答案
我终于找到了解决方案.Android 8.0,他们提供了公共api来打开/关闭热点.WifiManager
Finally I got the solution.Android 8.0, they provided public api to turn on/off hotspot. WifiManager
以下是开启热点的代码
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 reserved)
方法将在热点打开时调用.. 使用 WifiManager.LocalOnlyHotspotReservation
引用您调用 close()方法来关闭热点.
onStarted(WifiManager.LocalOnlyHotspotReservation reservation)
method will be called if hotspot is turned on.. Using WifiManager.LocalOnlyHotspotReservation
reference you call close()
method to turn off hotspot.
注意:要打开热点,应在设备中启用
Location(GPS)
.否则会抛出SecurityException
Note:To turn on hotspot, the
Location(GPS)
should be enabled in the device. Otherwise, it will throw SecurityException
这篇关于如何在 Android 8.0 (Oreo) 中以编程方式打开/关闭 wifi 热点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!