如何使用SUPPLICANT_STATE_CHANGED_ACTION WiFi BroadcastReceiver - android

时间:2012-01-13 08:35:13

标签: android android-intent broadcastreceiver wifimanager

我想在设备连接到wifi网络时在屏幕上显示连接过程。 SUPPLICANT_STATE_CHANGED_ACTION由WifiManager提供,但我不知道如何使用它。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:6)

您确实可以使用SUPPLICANT_STATE_CHANGED_ACTION广播的意图:

该应用需要其清单文件中的权限:

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

然后注册系统广播:

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

registerReceiver()需要一个实现BroadcastReceiver的类的实例作为其第一个参数。在该代码中,您可以通过覆盖onReceive方法来处理Wifi状态更改。例如

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:
                    ...
            }
        }
    }
}

有关可能的Wifi状态值,请参阅http://developer.android.com/reference/android/net/wifi/SupplicantState.html

答案 1 :(得分:3)

我不知道一个回调方法可以让你知道wifi状态何时发生了变化。我使用在后台运行的Handler轮询了这些信息。

将处理程序添加到您的类中。

private WifiStatusHandler wifiStatusHandler = new WifiStatusHandler();

通过调用

启动它
wifiStatusHandler.start();

我使用的代码如下。

/**
 * 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;
    }
}