我想列出Wifi网络。我在列表中寻找的是否有WiFi?我该如何控制它?我不想连接到wifi。如果你有一个特殊的WiFi网络,我想改变铃声模式。例如,ssid:" helloworld"。如果列表中有helloworld,我想改变铃声模式 - 你能帮助我吗?
答案 0 :(得分:1)
有两种情况,当WIFI
被禁用且启用WIFI
时,我写了两个AsyncTasks
来检查WIFI
状态并连接到您想要的{ {1}}。
SSID/Network
并像这样使用它们:
//Connect to SSID if WiFi is Enabled
public class ConnectToSSID extends AsyncTask<String, String, Boolean>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(MainActivity.this, "Connecting...",
"Connecting to \""+SSID+"\" Please Wait...", true);
}
@Override
protected Boolean doInBackground(String... params) {
final WifiManager wifiManager = (WifiManager) MainActivity.this.getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", SSID);
wifiConfig.preSharedKey = String.format("\"%s\"", NetworkPass);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
SystemClock.sleep(3000);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return wifi.isConnected();
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progress.dismiss();
if(result){
Toast.makeText(MainActivity.this,"Successfully Connected to "+SSID,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Error Connecting to "+SSID,Toast.LENGTH_LONG).show();
}
}
}
//IF WiFi is disabled, Enable it and Connect to SSID
public class EnableWifiAndConnectToSSID extends AsyncTask<String, String, Boolean>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(MainActivity.this, "Connecting...",
"Connecting to \""+SSID+"\" Please Wait...", true);
}
@Override
protected Boolean doInBackground(String... params) {
final WifiManager wifiManager = (WifiManager) MainActivity.this.getSystemService(Context.WIFI_SERVICE);
final WifiConfiguration config = new WifiConfiguration();
config.SSID = SSID;
config.preSharedKey = NetworkPass;
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
int networkId = wifiManager.addNetwork(config);
wifiManager.enableNetwork(networkId, true);
SystemClock.sleep(3000);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return wifi.isConnected();
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progress.dismiss();
if(result){
Toast.makeText(MainActivity.this,"Successfully Connected to "+SSID,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Error Connecting to "+SSID,Toast.LENGTH_LONG).show();
}
}
}