Issue
I am creating an application in which I am doing scan wifi, connect to selected wifi, and other wifi related tasks programmatically.Now I want to implement auto connect feature.
Requirement:If auto connect is ON, the info of wifi is cached and allow next time auto connects to network;
If multiple networks are set to Auto Connect, then it should connect to recently connected one.Any advise or guidance would be greatly appreciated.
Solution
Connecting app to wifi whenever wifi is enable. do steps for auto connect:
Register BroadcastReceiver().
<receiver
android:name=".MyReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Add permission in 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"/>
Create 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");
}
}
}
}
So whenever app is on foreground and wifi is enable to connect automatically recent wifi.
Answered By - Hemant Parmar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.