我需要在 Android 9.0 (Android P) 中进行什么 API 调用才能获取 Wifi 热点名称?
public static String getWifiApSSID(Context context) {
try {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Method method = manager.getClass().getDeclaredMethod("getWifiApConfiguration");
WifiConfiguration configuration = (WifiConfiguration) method.invoke(manager);
if (configuration != null) {
return configuration.SSID;
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return "";
}
Android 9.0 返回 ""
。
最佳答案
您正在使用反射方法 getWifiApiConfiguration
,该方法不适用于 API>=26。
好消息,对于 API>=26,您不需要使用反射。您可以使用 android 公开的 API,即 startLocalOnlyHotspot
它需要 Manifest.permission.CHANGE_WIFI_STATE
和 ACCESS_FINE_LOCATION
权限。
以下是如何使用此 API 打开热点的简单示例。
private WifiManager wifiManager;
WifiConfiguration currentConfig;
WifiManager.LocalOnlyHotspotReservation hotspotReservation;
开启热点的方法:
`
@RequiresApi(api = Build.VERSION_CODES.O)
public void turnOnHotspot() {
wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
@Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
hotspotReservation = reservation;
currentConfig = hotspotReservation.getWifiConfiguration();
Log.v("DANG", "THE PASSWORD IS: "
+ currentConfig.preSharedKey
+ " \n SSID is : "
+ currentConfig.SSID);
hotspotDetailsDialog();
}
@Override
public void onStopped() {
super.onStopped();
Log.v("DANG", "Local Hotspot Stopped");
}
@Override
public void onFailed(int reason) {
super.onFailed(reason);
Log.v("DANG", "Local Hotspot failed to start");
}
}, new Handler());
}
`
以下是获取本地创建的热点详细信息的方法
private void hotspotDetaisDialog()
{
Log.v(TAG, context.getString(R.string.hotspot_details_message) + "\n" + context.getString(
R.string.hotspot_ssid_label) + " " + currentConfig.SSID + "\n" + context.getString(
R.string.hotspot_pass_label) + " " + currentConfig.preSharedKey);
}
`
我最近创建了一个名为 Spotserve 的演示应用程序。这将为所有 API>=15 的设备打开 WiFi 热点,并在该热点上托管一个演示服务器。您可以检查以获取更多详细信息。希望这有帮助!
关于java - Android 9.0 wifi热点API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57290726/