How to use SUPPLICANT_STATE_CHANGED_ACTION WiFi Br

2019-07-04 04:32发布

I want to show the connection process on the screen when my device is connecting to the wifi network. SUPPLICANT_STATE_CHANGED_ACTION is provided by WifiManager but i don't know how to use it. Can anyone help me please?

2条回答
不美不萌又怎样
2楼-- · 2019-07-04 04:53

I don't know of a callback method that lets you know when the wifi status has changed. I polled the information using a Handler running in the background.

Add the handler to your class.

private WifiStatusHandler wifiStatusHandler = new WifiStatusHandler();

Start it by calling

wifiStatusHandler.start();

The code I used is below.

/**
 * Checks for wifi status updates.
 */
private class WifiStatusHandler extends Handler {
    private boolean running = false;

    public void handleMessage(Message message) {
        if (running) {
            //check wifi status here
            WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
            int curWifiState = wifiMgr.getWifiState();
            SupplicantState info = wifiMgr.getConnectionInfo().getSupplicantState();
            WifiInfo curWifi = wifiMgr.getConnectionInfo();
            Log.i(TAG,"WIFI STATE = " + info.toString());
            //update the TextView etc.
            sleep();
        }
    }

    private void sleep() {
        removeMessages(0);
        sendMessageDelayed(obtainMessage(0), REFRESH_DELAY);
    }

    public synchronized void start() {
        running = true;
        removeMessages(0);
        sendMessageDelayed(obtainMessage(0), 0);
    }

    public synchronized void stop() {
        running = false;
    }
}
查看更多
贪生不怕死
3楼-- · 2019-07-04 05:10

You can indeed use the broadcasted intents for SUPPLICANT_STATE_CHANGED_ACTION:

The app needs the permission in its Manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Then register for the system broadcast:

    MyWifiStateReceiver handler = new MyWifiStateReceiver();
    context.registerReceiver(handler, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));

the registerReceiver() needs an instance of a class implementing BroadcastReceiver as its first argument. In that code you can act on the Wifi state changes by overriding the onReceive method. For example

public class MyWifiStateReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION))
        {
            SupplicantState state = (SupplicantState) intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            switch(state)
            {
                case COMPLETED:
                case DISCONNECTED:
                    ...
            }
        }
    }
}

For the possible Wifi state values, see http://developer.android.com/reference/android/net/wifi/SupplicantState.html

查看更多
登录 后发表回答