如何在wifi上显示按钮连接?

时间:2013-09-04 15:24:47

标签: java android

在我的应用程序中,我以编程方式连接到wifi。有没有办法在wifi上显示一个按钮连接?

2 个答案:

答案 0 :(得分:3)

您可以使用this问题告诉您是否已连接到wifi。一旦你知道你是你就可以像往常一样显示你的按钮。

所以你的代码(取自Jason Knight的答案)将是:

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
    // show button 
}

答案 1 :(得分:2)

您需要实现BroadcastReceiver以侦听网络状态更改。

private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context c, Intent intent) {
        if (intent.getAction() == WifiManager.NETWORK_STATE_CHANGED_ACTION) {
            Bundle extras = Intent.getExtras();
            NetworkInfo ni = extras.get(EXTRA_NETWORK_INFO);
            if (ni.getState() == State.CONNECTED) {
                //show button
            } else {
                //hide button
            }
        } else if (intent.getAction() == WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION) {
            Bundle extras = Intent.getExtras();
            SupplicantState ss = extras.get(EXTRA_NEW_STATE);
            if (ss.getState() == COMPLETED) {
                //show button, note we may not have an IP address yet
            } else {
                //hide button
            }
            SupplicantState.COMPLETED
        }
    }
};

并且,在将显示按钮的活动的OnCreate()方法中的某处:

mWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);

//to listen to all network state changes (cell and wifi)
registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));

//to listen specifically to wifi changes
registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION));