How to detect when user turn one wifi connection to other wifi? - java

I have problem with WiFi connection detection. My goal is to detect when user is switching between different WiFis. I found this, but it only detects when WiFi was established. In my case I need to know when one WiFi network changed to another on phone.

You can use BroadcastReceiver
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
if(netInfo.isConnected()) {
WifiManager wifiManager = (WifiManager) context.getAplicationContext().getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();
String ssid = info.getSSID();
Log.d("Wifi Connected", "Wifi name is "+ info.getSSID());
}
}
}
}

Related

Updating textview data dynamically Android Java

I implemented the code to check wifi state connected or not. I made a text view
TextView WifiTv = (TextView) findViewById(R.id.wifistate);
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiCheck = connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiCheck.isConnected()) {
// Do whatever here
WifiTv.setText("WiFi is Connected");
WifiTv.notify();
} else {
WifiTv.setText("WiFi is not Connected");
}
It works but it does not update dynamically and therefore if I turn off wifi I have to refresh the activity for the textview to change (not data binded). How can I make the textview update without refresh please? Thx
EDIT: I have this code in a seperate class which works well with a toast. All I want to do is display in textview instead. How can I connect the textview variable to this class which does not have xml please?
public void onReceive(Context context, Intent intent) {
NetworkInfo info =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info != null && info.isConnected()) {
// Do your work.
// e.g. To check the Network Name or other info:
WifiManager wifiManager = (WifiManager)
context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Toast.makeText(context, "Connected to: " + ssid,
Toast.LENGTH_SHORT).show();
}
You required BroadcastReceiver and wifimanager. BroadcastReceiver which start when app launches to receive the the implicit intent every time. wifimanager to to check the status.
did you try to add a onResume function to check again each time you resume yout activity?
Don't know your app but maybe this,
#Override
protected void onResume() {
super.onResume();
if (wifiCheck.isConnected()) {
// Do whatever here
WifiTv.setText("WiFi is Connected");
WifiTv.notify();
} else {
WifiTv.setText("WiFi is not Connected");
}
}
If your others variables are not global to Activity, create them again within the onResume

Android: How to Scan WiFi, Connect to an AP and then Establish a TCP Connection?

I am writing an Android app. In my app, I want it to scan the WiFi network, and then connect to a dedicated Access Point (AP) by checking the SSID. And then after connected to the AP, establish a TCP connection to it.
Above I have described 3 tasks in order. I know how to do each task independently, however I do not know the proper way to finish them in sequence. Examples are appreciated.
Currently my code is to start scan the WiFi network whenever the user pressed a button by:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled() == false) {
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi is enabled", Toast.LENGTH_SHORT).show();
}
wifiManager.startScan();
I used a broadcast receiver to check when the scanning finished, and then invoke a method ( ReconnectAP() ) to connect WiFi to the AP. I also used the broadcast receiver to check when it connected to the AP, then I want to execute an Async Task to establish the TCP network. However, by googling, I learn that it is a bad practice to execute async task in a broadcast receiver, because the async task can be killed by Android when the receiver finished.
private String networkSSID = "The_AP_SSID";
// In onCreate of MainActivity, register the broadcast receiver:
registerReceiver(WiFireceiver, new IntentFilter(
WifiManager.NETWORK_STATE_CHANGED_ACTION));
registerReceiver(WiFireceiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
// Implement my broadcast receiver class:
BroadcastReceiver WiFireceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
Log.d(TAG, "WiFiReceiver received broadcast, action is SCAN_RESULTS_AVAILABLE_ACTION");
Log.d(TAG, "Start to check if need to reconnect to Charger AP");
ReconnectAP();
}
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
Log.d(TAG, "WiFiReceiver received broadcast, action is NETWORK_STATE_CHANGED_ACTION");
NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
// If the connection type is WiFi...
if (netInfo != null && ConnectivityManager.TYPE_WIFI == netInfo.getType()) {
// If it is connected now....
if (netInfo.isConnected()) {
Log.d(TAG, "WiFi connected");
// Get WiFi connection information, eg SSID
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.d(TAG, "WiFi connected SSID is : " + ssid);
if(ssid.equals(networkSSID)) {
// Start async task to establish a TCP connection:
new ConnectTCPAsynTask().execute();
}
} else {
Log.d(TAG, "WiFi disconnected");
}
}
}
}
};
int ReconnectAP() {
Log.d(TAG, "In ReconnectAP( )");
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.d(TAG, "Original connected AP SSID: " + ssid);
if (!ssid.equals(networkSSID)) {
Log.d(TAG, "It is not equal to the dedicated AP SSID,
we will disconnect the current WiFi connection,
and then connect to our dedicate AP");
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
Log.d(TAG, "Start disconnect and reconnect to " + networkSSID);
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
return 1;
}
}
Log.d(TAG,"Reach here if cannot find the target SSID");
return -1;
}
Log.d(TAG, "Reach here if we already connected to the dedicated AP");
return 0;
}
Pass a flag from the broadcast receiver back to the main activity and let the main activity handle the task.

Reconnecting to a WiFi Network after disconnecting from it Programatically

I got disconnected from a WiFi network Programatically using
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.disconnect();
DisconnectWifi discon = new DisconnectWifi();
registerReceiver(discon, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
public class DisconnectWifi extends BroadcastReceiver {
#Override
public void onReceive(Context c, Intent intent) {
WifiManager wifi = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
if(!intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE).toString().equals(SupplicantState.SCANNING))
wifi.disconnect();
}
}
But I am not able to reconnect to the same network again. I tried reconnecting by using:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.reconnect();
but was not able to connect. How can I now reconnect to WiFi Network?
Thanks,
So the complete, simplified solution would look something like this:
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);
WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
Hope it Helps You!!

Trigger some code as soon as android app detects a particular Wi-Fi network

Im developing an android app. For this app to work the Wi-Fi needs to be enabled all the time. Because the Wi-Fi is enabled it will keep on scanning for available networks.
I want some function to be called as soon as the Wi-Fi connects to a particular network.
How do I achieve this?
I have written the following code but this works only once, how do I make this scan for networks continuously?
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifi.isConnected()){
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) {
String ssid = connectionInfo.getSSID();
}
Log.i("wifi", "connected");
}
else{
Log.i("wifi", "not connected");
}
Follow the steps and do a trick
1) Create NetworkChangeReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
public static boolean isWifiConnected = true;
public static final String tag = "NETWORKCHANGERECEIVER";
#Override
public void onReceive(final Context context, final Intent intent) {
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifi.isConnected()) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) {
String ssid = connectionInfo.getSSID();
}
isWifiConnected = true;
Log.i("wifi", "connected");
} else {
Log.i("wifi", "not connected");
isWifiConnected = false;
}
}
}
2) Add this line to Manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<receiver android:name="com.df.src.NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
You should use a BroadcastReceiver in your application to get instant notifications about connectivity changes.
Some reference that may help you:
http://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/
http://developerandro.blogspot.com/2013/09/check-internet-connection-using.html?m=1
http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

Wait for network connection

I need to make my app wait until a wifi connection is fully established and only then continue to run.
I have this code for now:
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if(!wifiManager.isWifiEnabled())
{
Toast.makeText(this, "Connecting to wifi network", Toast.LENGTH_SHORT).show();
wifiManager.setWifiEnabled(true);
//wait for connection to be establisihed and only then proceed
}
You can use a broadcast receiver registered for:
android.net.conn.CONNECTIVITY_CHANGE
listen the status changes and keep a variable with the current status
More information here
<receiver android:name="your.package.WifiReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
And the Receiver:
public class WifiReceiver extends BroadcastReceiver {
public static boolean connected = false;
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager mgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = mgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
connected = networkInfo != null && networkInfo.isConnected();
}
}
public boolean isConnected(){
return connected;
}
Instead of blocking the main thread, you could introduce a screen to the users with a connection notification to let them know what's happening.
While showing a screen with the notification you could check for a connection using the
ConnectivityManager
Note that checking only a WIFI connection will not guarantee a data service. Network issues, server downtime, authorization, etc. could always occur.
Example of usage:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Also, don't forget to add the right permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You can find more about this on the Android Developer website:
Determining and Monitoring the Connectivity Status
Good luck.

Categories

Resources