问题描述
要获取Wifi热点名称,我需要在Android 9.0(Android P)中进行什么API调用?
What is the API call I need to make in Android 9.0 (Android P) to get a Wifi hotspot name?
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返回""
.
Android 9.0 returns ""
.
推荐答案
您正在使用反射方法getWifiApiConfiguration
,该方法不适用于API> = 26.好消息,对于API> = 26,您不需要使用反射.您可以通过android使用公开的公开API,例如 startLocalOnlyHotspot
You're using reflection method getWifiApiConfiguration
which doesn't works for API>=26.Good news, for API>=26, you don't need to use reflection. You can just use the public exposed API by android i.e. startLocalOnlyHotspot
它需要Manifest.permission.CHANGE_WIFI_STATE
和ACCESS_FINE_LOCATION
权限.
这是一个简单的示例,说明如何使用此API打开热点.
Here's a simple example of how you can turn on hotspot using this 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());
}
`
在这里,您可以获取本地创建的热点的详细信息
Here's how you can get details of the locally created hotspot
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热点,并在该热点上托管一个演示服务器.您可以检查以获取更多详细信息.希望这会有所帮助!
I recently created a demo app called Spotserve. That turns on wifi hotspot for all devices with API>=15 and hosts a demo server on that hotspot. You can check that for more details. Hope this helps!
这篇关于Android 9.0 wifi热点API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!