Android O提供wifiManager.startLocalOnlyHotspot创建一个封闭的网络。为了设计快捷方式或窗口来切换这种热点,我如何知道LocalOnlyHotspot的状态来判断是启动还是关闭它?
当我启动localOnlyHotspot时,其他设备如何连接到它? (如何获取密码?)
答案 0 :(得分:0)
此代码可以帮助您使其运行。我实现了一个Hotspotmanager类,该类可以在应用程序中使用。打开热点后,它将向侦听器传递一个wificonfiguration对象,您必须在呼叫活动中实现该对象。从此配置中,您可以获取SSID和preSharedKey。注意:SSID和密码无法更改!!!因为创建过程完全隐藏在Androids系统API中。
public class HotspotManager {
private final WifiManager wifiManager;
private final OnHotspotEnabledListener onHotspotEnabledListener;
private WifiManager.LocalOnlyHotspotReservation mReservation;
public interface OnHotspotEnabledListener{
void OnHotspotEnabled(boolean enabled, @Nullable WifiConfiguration wifiConfiguration);
}
//call with Hotspotmanager(getApplicationContext().getSystemService(Context.WIFI_SERVICE),this) in an activity that implements the Hotspotmanager.OnHotspotEnabledListener
public HotspotManager(WifiManager wifiManager, OnHotspotEnabledListener onHotspotEnabledListener) {
this.wifiManager = wifiManager;
this.onHotspotEnabledListener = onHotspotEnabledListener;
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void turnOnHotspot() {
wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
@Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
mReservation = reservation;
onHotspotEnabledListener.OnHotspotEnabled(true, mReservation.getWifiConfiguration());
}
@Override
public void onStopped() {
super.onStopped();
}
@Override
public void onFailed(int reason) {
super.onFailed(reason);
}
}, new Handler());
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void turnOffHotspot() {
if (mReservation != null) {
mReservation.close();
onHotspotEnabledListener.OnHotspotEnabled(false, null);
}
}