下面列出了怎么用android.net.wifi.SupplicantState的API类实例代码及写法,或者点击链接到github查看源代码。
public String getCurrentWifiSSID()
{
WifiManager wifiManager = (WifiManager) MainActivity.mainActivity.getApplicationContext().getSystemService(MainActivity.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();
String ssid = info.getSSID();
if (info.getSupplicantState() != SupplicantState.COMPLETED)
{
MainActivity.log("OBConnectionManager:getCurrentWifiSSID. not connected to current wifi. returning null");
return null;
}
if (ssid.charAt(0) == '"' && ssid.charAt(ssid.length() - 1) == '"')
{
return ssid.substring(1, ssid.length() - 1);
}
else
{
return ssid;
}
}
@SuppressWarnings("ResourceType") @Test //
public void supplicantStateChanges() throws IllegalAccessException, InstantiationException {
Application application = RuntimeEnvironment.application;
TestSubscriber<SupplicantStateChangedEvent> o = new TestSubscriber<>();
RxWifiManager.supplicantStateChanges(application).subscribe(o);
o.assertValues();
Intent intent1 = new Intent(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION) //
.putExtra(EXTRA_NEW_STATE, (Parcelable) SupplicantState.INACTIVE)
.putExtra(EXTRA_SUPPLICANT_ERROR, ERROR_AUTHENTICATING);
application.sendBroadcast(intent1);
SupplicantStateChangedEvent event1 =
SupplicantStateChangedEvent.create(SupplicantState.INACTIVE, ERROR_AUTHENTICATING);
o.assertValues(event1);
Intent intent2 = new Intent(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION) //
.putExtra(EXTRA_NEW_STATE, (Parcelable) SupplicantState.ASSOCIATING)
.putExtra(EXTRA_SUPPLICANT_ERROR, -1);
application.sendBroadcast(intent2);
SupplicantStateChangedEvent event2 =
SupplicantStateChangedEvent.create(SupplicantState.ASSOCIATING, -1);
o.assertValues(event1, event2);
}
@Override
public void onReceive(Context context, Intent intent) {
if (!WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
return;
}
mLock.lock();
WifiInfo info = mWifiManager.getConnectionInfo();
if ( info.getNetworkId()==mNetworkID && info.getSupplicantState() == SupplicantState.COMPLETED ) {
mIsConnnected = true;
mCondition.signalAll();
}
mLock.unlock();
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(BuildConfig.DEBUG) Logger.debug(TAG, "onReceive:" + action);
if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION .equals(action)) {
SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if(state == SupplicantState.COMPLETED) {
final WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
if(wifiManager != null) {
WifiInfo info = wifiManager.getConnectionInfo();
if (info != null) {
mContext = context;
onWiFiConnected(info.getSSID());
}
}
}
}
}
@RequiresPermission(allOf = {Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE})
private String fetchWiFiSSID() {
String ssid = null;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
ssid = wifiInfo.getSSID();
ssid = ssid.replace("\"", "");
}
Log.e(TAG, "Returning ssid : " + ssid);
return ssid;
}
private String getWifiSsid() {
String ssid = null;
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
ssid = wifiInfo.getSSID();
ssid = ssid.replace("\"", "");
}
return ssid;
}
/**
* Check whether WiFi is connected
* @param context a Context instance
* @return true if Wifi is connected
*/
// @RequiresPermission(value = Manifest.permission.ACCESS_WIFI_STATE)
public static boolean isWifiConnected(Context context) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager == null || !wifiManager.isWifiEnabled()) return false;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo == null || wifiInfo.getNetworkId() == -1) return false;
return wifiInfo.getSupplicantState() == SupplicantState.ASSOCIATED;
}
private JSONObject serializeWifiInfo(WifiInfo data) throws JSONException {
JSONObject result = new JSONObject(mGson.toJson(data));
result.put("SSID", trimQuotationMarks(data.getSSID()));
for (SupplicantState state : SupplicantState.values()) {
if (data.getSupplicantState().equals(state)) {
result.put("SupplicantState", state.name());
}
}
return result;
}
@Nullable
public static EventNetworkChange grabNetworkStatus(final Context context) {
EventNetworkChange event = new EventNetworkChange();
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) return null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI && activeNetwork.isConnected()) {
event.setWifiConnected(true);
WifiManager wifiManager = (WifiManager) MainApp.instance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
event.setSsid(wifiInfo.getSSID());
}
if (L.isEnabled(L.CORE))
log.debug("NETCHANGE: Wifi connected. SSID: " + event.connectedSsid());
}
}
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
event.setMobileConnected(true);
event.setRoaming(activeNetwork.isRoaming());
if (L.isEnabled(L.CORE))
log.debug("NETCHANGE: Mobile connected. Roaming: " + event.getRoaming());
}
} else {
if (L.isEnabled(L.CORE))
log.debug("NETCHANGE: Disconnected.");
}
lastEvent = event;
return event;
}
private void onNetworkChanged(final WifiInfo wifiInfo) {
mExecutor.execute(new Runnable() {
@Override
public void run() {
synchronized (this) {
mLogger.info("onNetworkChanged: state=" + wifiInfo.getSupplicantState());
if (wifiInfo.getSupplicantState() != SupplicantState.COMPLETED) {
return;
}
mLogger.info("onNetworkChanged: SSID=" + wifiInfo.getSSID());
ThetaDevice oldDevice = mConnectedDevice;
if (oldDevice != null && oldDevice.getName().equals(wifiInfo.getSSID())) {
mLogger.info("onNetworkChanged: Connected already: SSID=" + wifiInfo.getSSID());
return;
}
ThetaDevice newDevice = ThetaDeviceFactory.createDeviceFromAccessPoint(mContext, wifiInfo);
mLogger.info("onNetworkChanged: THETA Device: " + newDevice);
if (isLostOldDevice(oldDevice, newDevice)) {
mLogger.info("onNetworkChanged: isLostOldDevice: " + oldDevice.getId());
notifyOnThetaLost(oldDevice);
oldDevice.destroy();
}
if (isFoundNewDevice(oldDevice, newDevice)) {
mLogger.info("onNetworkChanged: isFoundNewDevice: " + newDevice.getId());
notifyOnThetaDetected(newDevice);
}
mConnectedDevice = newDevice;
}
}
});
}
/** TODO: docs. */
@CheckResult @NonNull //
public static Observable<SupplicantStateChangedEvent> //
supplicantStateChanges(@NonNull final Context context) {
checkNotNull(context, "context == null");
IntentFilter filter = new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
return RxBroadcastReceiver.create(context, filter)
.map(new Func1<Intent, SupplicantStateChangedEvent>() {
@Override public SupplicantStateChangedEvent call(Intent intent) {
SupplicantState newState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 0);
return SupplicantStateChangedEvent.create(newState, error);
}
});
}
/**
* This method connects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network connected, false if failed
*/
private boolean connectNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: connectNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: connectNetwork invalid data");
Log.d(TAG, "WifiWizard: connectNetwork invalid data.");
return false;
}
String ssidToConnect = "";
try {
ssidToConnect = data.getString(0);
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
int networkIdToConnect = ssidToNetworkId(ssidToConnect);
if (networkIdToConnect >= 0) {
// We disable the network before connecting, because if this was the last connection before
// a disconnect(), this will not reconnect.
wifiManager.disableNetwork(networkIdToConnect);
wifiManager.enableNetwork(networkIdToConnect, true);
SupplicantState supState;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();
callbackContext.success(supState.toString());
return true;
}else{
callbackContext.error("WifiWizard: cannot connect to network");
return false;
}
}
public void startServer(Handler handler, String documentRoot, int port) {
try {
isRunning = true;
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intToIp(wifiInfo.getIpAddress());
if( wifiInfo.getSupplicantState() != SupplicantState.COMPLETED) {
new AlertDialog.Builder(this).setTitle("Error").setMessage("Please connect to a WIFI-network for starting the webserver.").setPositiveButton("OK", null).show();
throw new Exception("Please connect to a WIFI-network.");
}
server = new Server(handler, documentRoot, ipAddress, port, getApplicationContext());
server.start();
Intent i = new Intent(this, StartActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
updateNotifiction("Webserver is running on port " + ipAddress + ":" + port);
Message msg = new Message();
Bundle b = new Bundle();
b.putString("msg", "Webserver is running on port " + ipAddress + ":" + port);
msg.setData(b);
handler.sendMessage(msg);
} catch (Exception e) {
isRunning = false;
Log.e("Webserver", e.getMessage());
updateNotifiction("Error: " + e.getMessage());
}
}
private WifiInfo getConnectionInfo() {
WifiManager manager = (WifiManager) getActivity().getSystemService(Activity.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
if (info != null) {
SupplicantState state = info.getSupplicantState();
if (state.equals(SupplicantState.COMPLETED)) {
return info;
}
}
return null;
}
private WifiInfo getConnectionInfo() {
Object service = getSystemService(WIFI_SERVICE);
WifiManager manager = (WifiManager) service;
WifiInfo info = manager.getConnectionInfo();
if (info != null) {
SupplicantState state = info.getSupplicantState();
if (state.equals(SupplicantState.COMPLETED)) {
return info;
}
}
return null;
}
/**
* This method retrieves the WifiInformation for the (SSID or BSSID) currently connected network.
*
* @param callbackContext A Cordova callback context
* @param basicIdentifier A flag to get BSSID if true or SSID if false.
* @return true if SSID found, false if not.
*/
private boolean getWifiServiceInfo(CallbackContext callbackContext, boolean basicIdentifier) {
if (API_VERSION >= 23 && !cordova.hasPermission(ACCESS_FINE_LOCATION)) { //Android 9 (Pie) or newer
requestLocationPermission(WIFI_SERVICE_INFO_CODE);
bssidRequested = basicIdentifier;
return true;
} else {
WifiInfo info = wifiManager.getConnectionInfo();
if (info == null) {
callbackContext.error("UNABLE_TO_READ_WIFI_INFO");
return false;
}
// Only return SSID or BSSID when actually connected to a network
SupplicantState state = info.getSupplicantState();
if (!state.equals(SupplicantState.COMPLETED)) {
callbackContext.error("CONNECTION_NOT_COMPLETED");
return false;
}
String serviceInfo;
if (basicIdentifier) {
serviceInfo = info.getBSSID();
} else {
serviceInfo = info.getSSID();
}
if (serviceInfo == null || serviceInfo.isEmpty() || serviceInfo == "0x") {
callbackContext.error("WIFI_INFORMATION_EMPTY");
return false;
}
// http://developer.android.com/reference/android/net/wifi/WifiInfo.html#getSSID()
if (serviceInfo.startsWith("\"") && serviceInfo.endsWith("\"")) {
serviceInfo = serviceInfo.substring(1, serviceInfo.length() - 1);
}
callbackContext.success(serviceInfo);
return true;
}
}
@Override
public void onReceive(final Context context, @NonNull final Intent intent) {
final String action = intent.getAction();
wifiLog("Connection Broadcast action: " + action);
if (Objects.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION, action)) {
/*
Note here we dont check if has internet connectivity, because we only validate
if the connection to the hotspot is active, and not if the hotspot has internet.
*/
if (isAlreadyConnected(mWifiManager, of(mScanResult).next(scanResult -> scanResult.BSSID).get())) {
handler.removeCallbacks(handlerCallback);
mWifiConnectionCallback.successfulConnect();
}
} else if (Objects.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION, action)) {
final SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
final int supl_error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
if (state == null) {
handler.removeCallbacks(handlerCallback);
mWifiConnectionCallback.errorConnect(ConnectionErrorCode.COULD_NOT_CONNECT);
return;
}
wifiLog("Connection Broadcast action: " + state);
switch (state) {
case COMPLETED:
case FOUR_WAY_HANDSHAKE:
if (isAlreadyConnected(mWifiManager, of(mScanResult).next(scanResult -> scanResult.BSSID).get())) {
handler.removeCallbacks(handlerCallback);
mWifiConnectionCallback.successfulConnect();
}
break;
case DISCONNECTED:
if (supl_error == WifiManager.ERROR_AUTHENTICATING) {
wifiLog("Authentication error...");
handler.removeCallbacks(handlerCallback);
mWifiConnectionCallback.errorConnect(ConnectionErrorCode.AUTHENTICATION_ERROR_OCCURRED);
} else {
wifiLog("Disconnected. Re-attempting to connect...");
reEnableNetworkIfPossible(mWifiManager, mScanResult);
}
}
}
}
public void connectToNetwork_connectToWifi (final String ssid, final String password, final OBUtils.RunLambdaWithSuccess block)
{
if (ssid == null)
return;
//
final WifiManager wfMgr = (WifiManager) MainActivity.mainActivity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//
String connectionSSID = wfMgr.getConnectionInfo().getSSID();
if (connectionSSID.startsWith("\"") && connectionSSID.endsWith("\""))
{
connectionSSID = connectionSSID.substring(1, connectionSSID.length() - 1);
}
//
SupplicantState connectionState = wfMgr.getConnectionInfo().getSupplicantState();
//
MainActivity.log("OBConnectionManager.connectToNetwork_connectToWifi. [" + connectionSSID + "] - [" + connectionState.toString() + "]");
//
if (connectionSSID.equals(ssid) && connectionState == SupplicantState.COMPLETED)
{
MainActivity.log("OBConnectionManager.connectToNetwork_connectToWifi. already connected to the network");
connectToNetWork_complete(true, block);
}
else if (!ssid.equals(connectionSSID) && connectionState == SupplicantState.COMPLETED)
{
MainActivity.log("OBConnectionManager.connectToNetwork_connectToWifi. Connected to OTHER Wifi. Disconnecting current WiFi");
//
int currentNetworkID = wfMgr.getConnectionInfo().getNetworkId();
//
boolean networkDisabled = wfMgr.disableNetwork(currentNetworkID);
boolean configurationSaved = wfMgr.saveConfiguration();
boolean disconnected = wfMgr.disconnect();
//
if (!networkDisabled || !configurationSaved || !disconnected)
{
MainActivity.log("OBConnectionManager.connectToNetwork_connectToWifi. FAILED to disconnect from current WiFi. Aborting operation");
}
else
{
connectToNetwork_disableAirplaneMode(ssid, password, block);
}
}
else
{
MainActivity.log("OBConnectionManager.connectToNetwork_connectToWifi. Wifi not connected. Go to check airplane, enable wifi and scan");
connectToNetwork_disableAirplaneMode(ssid, password, block);
//connectToNetwork_scanForWifi(ssid, password, block);
}
}
public void onReceive(Context context, Intent intent) {
this.context = context;
this.intent = intent;
// Stop if Intent is empty
if (intent == null || intent.getAction() == null)
return;
// Stop if automatic connection is disabled in settings
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
if (!settings.getBoolean("pref_autoconnect", true))
return;
// If Wi-Fi is disabled, stop ConnectionService immediately
WifiUtils wifi = new WifiUtils(context);
if (!wifi.isEnabled()) {
Logger.log(this, "Wi-Fi not enabled");
stopService();
return;
}
SupplicantState state = null;
/**
* Listen to all Wi-Fi state changes and start ConnectionService if Wi-Fi is connected
*/
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
state = wifi.getWifiInfo(intent).getSupplicantState();
}
/**
* Catch extra SupplicantState broadcast for devices that are skipping
* STATE_CHANGE with state == DISCONNECTED
*/
if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
}
if (state != null) {
Logger.log(this, String.format(Locale.ENGLISH, "Intent: %s (%s)",
intent.getAction(), state.name()
));
switch (state) {
case COMPLETED:
case ASSOCIATED: // This appears randomly between multiple CONNECTED states
startService();
break;
case SCANNING: // Some devices do not report DISCONNECTED state so...
case DISCONNECTED:
stopService();
break;
default:
Logger.log(this, "Unknown SupplicantState: " + state.name());
}
} else {
Logger.log(this, "Unknown Intent: " + intent.getAction());
}
}
@CheckResult @NonNull //
public static SupplicantStateChangedEvent create(@NonNull SupplicantState newState, int error) {
Preconditions.checkNotNull(newState, "newState == null");
return new AutoValue_SupplicantStateChangedEvent(newState, error);
}
public static boolean connectToWifi(Context context, final String ssid, String password) {
int networkId = -1;
int c;
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifiManager == null) {
Logger.error(TAG, "No WiFi manager");
return false;
}
List<WifiConfiguration> list;
if (wifiManager.isWifiEnabled()) {
list = wifiManager.getConfiguredNetworks();
} else {
if (!wifiManager.setWifiEnabled(true)) {
Logger.error(TAG, "Enable WiFi failed");
return false;
}
c = 0;
do {
Utils.sleep(500);
list = wifiManager.getConfiguredNetworks();
} while (list == null && ++c < 10);
}
if (list == null) {
Logger.error(TAG, "Could not get WiFi network list");
return false;
}
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
networkId = i.networkId;
break;
}
}
WifiInfo info;
if (networkId < 0) {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + ssid + "\"";
conf.preSharedKey = "\"" + password + "\"";
networkId = wifiManager.addNetwork(conf);
if (networkId < 0) {
Logger.error(TAG, "New WiFi config failed");
return false;
}
} else {
info = wifiManager.getConnectionInfo();
if (info != null) {
if (info.getNetworkId() == networkId) {
if(Logger.DEBUG) Logger.debug(TAG, "Already connected to " + ssid);
return true;
}
}
}
if (!wifiManager.disconnect()) {
Logger.error(TAG, "WiFi disconnect failed");
return false;
}
if (!wifiManager.enableNetwork(networkId, true)) {
Logger.error(TAG, "Could not enable WiFi.");
return false;
}
if (!wifiManager.reconnect()) {
Logger.error(TAG, "WiFi reconnect failed");
return false;
}
c = 0;
do {
info = wifiManager.getConnectionInfo();
if (info != null && info.getNetworkId() == networkId &&
info.getSupplicantState() == SupplicantState. COMPLETED && info.getIpAddress() != 0) {
if(Logger.DEBUG) Logger.debug(TAG, "Successfully connected to %s %d", ssid, info.getIpAddress());
return true;
}
Utils.sleep(500);
} while (++c < 30);
Logger.error(TAG, "Failed to connect to " + ssid);
return false;
}
private void getWiFiInfo()
{
initNetwork();
if (wifiManager != null)
{
final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
fullInfo.setProperty("WIFI_SSID",
String.valueOf(Helperfunctions.removeQuotationsInCurrentSSIDForJellyBean(wifiInfo.getSSID())));
/*
* fullInfo.setProperty("WIFI_LINKSPEED",
* String.valueOf(wifiInfo.getLinkSpeed()));
*/
fullInfo.setProperty("WIFI_BSSID", String.valueOf(wifiInfo.getBSSID()));
fullInfo.setProperty("WIFI_NETWORK_ID", String.valueOf(wifiInfo.getNetworkId()));
/*
* fullInfo.setProperty("WIFI_RSSI",
* String.valueOf(wifiInfo.getRssi()));
*/
final SupplicantState wifiState = wifiInfo.getSupplicantState();
fullInfo.setProperty("WIFI_SUPPLICANT_STATE", String.valueOf(wifiState.name()));
final DetailedState wifiDetail = WifiInfo.getDetailedStateOf(wifiState);
fullInfo.setProperty("WIFI_SUPPLICANT_STATE_DETAIL", String.valueOf(wifiDetail.name()));
if (getNetwork() == NETWORK_WIFI)
{
final int rssi = wifiInfo.getRssi();
if (rssi != -1 && rssi >= ACCEPT_WIFI_RSSI_MIN)
{
int linkSpeed = wifiInfo.getLinkSpeed();
if (linkSpeed < 0) {
linkSpeed = 0;
}
final SignalItem signalItem = SignalItem.getWifiSignalItem(linkSpeed, rssi);
if (this.collectInformation) {
signals.add(signalItem);
}
lastSignalItem.set(signalItem);
signal.set(rssi);
signalType.set(SINGAL_TYPE_WLAN);
// Log.i(DEBUG_TAG, "Signals1: " + signals.toString());
}
}
}
}
public abstract @NonNull SupplicantState newState();