在我的应用程序中,我以编程方式连接到 wifi。有没有办法让我在 wifi 连接时显示一个按钮?
问问题
87 次
2 回答
3
您可以使用此问题来告诉您是否已连接到 wifi。一旦你知道你是你,你就可以像往常一样显示你的按钮。
因此,您的代码(取自 Jason Knight 的回答)将是:
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// show button
}
于 2013-09-04T15:29:45.790 回答
2
You will need to implement a BroadcastReceiver to listen for network state changes.
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
}
}
};
and, somewhere in the OnCreate()
method of the Activitys that will display the button:
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));
于 2013-09-04T15:55:09.370 回答