3

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

4

2 回答 2

7

您确实可以将广播的意图用于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

于 2014-11-30T17:17:34.497 回答
3

我不知道有什么回调方法可以让您知道 wifi 状态何时发生变化。我使用在后台运行的处理程序轮询信息。

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

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;
    }
}
于 2012-09-13T19:58:17.070 回答