我正在创建一个应用程序,其中我正在扫描wifi,连接到选定的wifi,以及其他与编程相关的任务。现在我想实现自动连接功能。
要求:如果自动连接为ON,则缓存wifi信息并允许下次自动连接到网络;
如果多个网络设置为自动连接,那么它应该连接到最近连接的网络。任何建议或指导将不胜感激。
答案 0 :(得分:1)
启用wifi后,将应用程序连接到wifi。执行自动连接的步骤:
注册BroadcastReceiver().
<receiver
android:name=".MyReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
在Menifest中添加权限。
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
创建MyReceiver
:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.d("MyReceiver", "MyReceiver invoked...");
WifiManager wifiManager = (WifiManager)
context.getSystemService(context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (!noConnectivity) {
Log.d("MyReceiver", "connected");
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid );
wifiConfig.preSharedKey = String.format("\"%s\"", networkKey);
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
}
else{
Log.d("NetworkCheckReceiver", "disconnected");
}
}
}
}
因此,只要应用程序位于前台,并且启用了wifi即可自动连接最近的wifi。