Get WIFI ID from last connected WIFI - android

I'm writing an Android application which should react if the phone connects or disconnects to a WIFI network. I registered a BroadcastReceiver for this and it works great. Now with this code I'm able to get the current WIFI ID if the phone is connected to a WIFI:
WifiManager mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo currentWifi = mainWifi.getConnectionInfo();
int id = currentWifi.getNetworkId();
But what if the WIFI disconnects and I want to get the WIFI ID of the last connected WIFI? My problem is that all this is in an BroadcastReceiver. This is allways new created if a new Broadcast comes in so I can not really save some data there. Is there a method or something else with which I can get the last connected WIFI ID?

Forgive me if I'm missing something. You could getSharedPreferences to have a context to access from Broadcast receiver.
This BroadcastReceiver intercepts the android.net.ConnectivityManager.CONNECTIVITY_ACTION, which indicates a connection change. It checks whether the type is TYPE_WIFI. If it is, it checks whether Wi-Fi is connected and sets the wifiConnected flag in the main activity accordingly.
public class NetworkReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// Checks the user prefs and the network connection. Based on the result, decides
// whether
// to refresh the display or keep the current display.
// If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
if (WIFI.equals(sPref) && networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// If device has its Wi-Fi connection, sets refreshDisplay
// to true. This causes the display to be refreshed when the user
// returns to the app.
You can find here the sample app.

Related

detect if wifi connection offers internet access android studio

I'm currently working on an application that needs to know whether the phone has internet connection.
Using Connectivity Manager the app is able to generate an event when there is or there is no network connection. Problem is, I need to be connected to a WI-FI local hotspot for my app, and this WI-FI does not offer internet access. to summarise, ConnectivityManager tells me there is internet connection because i'm connected to this wi-fi, but this wi-fi does not offer a real connection.
Here is the code :
public void onReceive(Context context, Intent intent) {
if(intent == null || intent.getExtras() == null)
return;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
connected = false;
}
notifyStateToAll();
}
Is there a way to specify ConnectivityManager that one special Wi-Fi does not offer internet access?

get notification before connectivity changes

I am working over a project. In this, I am running a background service, in this their is connection between device and server. I want when device is connected to internet the service gets started and connection gets builtup between server and device and when internet disconnected the connection between server and device also gets disconnected
For this I have to send request to disconnect the connection, but that also requires internet connection that is currently not available.
So I want to disconnect the connection between server and device before internet gets disconnected. For this I need the stage i.e prior to internet disconnected that may be like Going to disconnect internet.
The code I tried is not sufficient for this work
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
try{
if(netInfo.isConnected() && netInfo != null){
System.out.println("Connected to internet");
context.startService(new Intent(context,MessageService.class));
}
}catch(NullPointerException e){
System.out.println("Not Connected to internet");
context.stopService(new Intent(context,MessageService.class));
}
}
}
Can anyone tell any soln for this?

Detect BSSID changes Constantly

I am developing an android application that is supposed to constantly check the BSSID of the access point to which the phone is connected, knowing that the phone will always be connected to one network but may connect to multiple access points (Not at the same time, of course) since the building is big. I used a BroadcastReceiver but to check whether the phone got connected to a different access point, I have to close the application and run it again to get the updated BSSID. I want the application to constantly check and update the UI with the new BSSID without me having to close the application and open it again. Do you have any idea how I can do that?
Thank you
I have sucessfully used this in the past to monitor for WiFi connection changes:
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
// etc
}
}
}
Just register your receiver in onResume() and unregister it in onPause() and you should be good to go.
#Override
protected void onResume() {
super.onResume();
IntentFilter connectivityFilter = new IntentFilter();
connectivityFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(your_broadcast_receiver, connectivityFilter);
}

Can android differentiate between a lost internet connection and no internet connect?

When I press a button on my app to open an image it shows a progress bar of the image being downloaded and then it opens. If there is no wifi connection it displays an error message saying "No wifi". I have used the code below to check for a wifi connection:
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork.isConnectedOrConnecting();
boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
I want to implement an error message that is displayed when the connection is lost. So if you click on the image and while its downloading you turn off the wifi then it displays a message saying "wifi disconnected".
Is this possible? Whether a connection is lost or there is no wifi all you are doing is checking if there is a connection available which is the same thing
You need to use a BroadcastReceiver that will be triggered when the connectivity status for Wi-Fi has changed.
Set following things before registering BroadcastReceiver:
private class ConnectionChangeReceiver extends BroadcastReceiver {
public void onReceive( Context context, Intent intent ) {
Log.d(tag, "Inside Broadcast Reciever");
CheckWifiStatus();
}
}
private void RegisterWifiWatcher()
{
if(wifiWatcher == null)
wifiWatcher = new ConnectionChangeReceiver();
final IntentFilter intentFilter= new IntentFilter();
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE");
registerReceiver(wifiWatcher, intentFilter);
}
WIFI_STATE_CHANGED :
Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown.
Permissions in Manifest :
<user-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<user-permission android:name="android.permission.ACCESS_WIFI_STATE" />
NOTE:
The broadcast intents that we receive for the different WiFi states have extras along with them that you can access to determine the different states of the WiFi connection.
Sure its possible. Adding to the above answer another option:
You can check with your code if wifi is available first.
Then start downloading the image and if you catch an exception during that time, toast the message wi-fi disconnected.

Restrict network access to only via WiFi

it is no problem to check if a valid WiFi connection exists. But how can I ensure only this WiFi connection is used for network access?
Assumed following scenario:
I check if a valid WiFi-connection exists (and may be I verify if a working Internet connection exists too)
now this WiFi connection is interrupted
I start transmitting data over network and now the mobile connection is used because WiFi died recently
How can I avoid that?
Check if WiFi connection exists:
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
Source, or use this code snippet:
private static final String DEBUG_TAG = "NetworkStatusExample";
...
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();
networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();
Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);
Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);
Add a Listener to check if WiFi is still enabled:
public class NetworkReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conn = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
// Checks the user prefs and the network connection. Based on the result, decides whether
// to refresh the display or keep the current display.
// If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
if (WIFI.equals(sPref) && networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// If device has its Wi-Fi connection, sets refreshDisplay
// to true. This causes the display to be refreshed when the user
// returns to the app.
refreshDisplay = true;
Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
// If the setting is ANY network and there is a network connection
// (which by process of elimination would be mobile), sets refreshDisplay to true.
} else if (ANY.equals(sPref) && networkInfo != null) {
refreshDisplay = true;
// Otherwise, the app can't download content--either because there is no network
// connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
// is no Wi-Fi connection.
// Sets refreshDisplay to false.
} else {
refreshDisplay = false;
Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
}
}
Please read Managing Network Usage for a detailed solution
You can add broad cast receiver for network changes. So whenever wifi get interrupted you will get the notification and you can handle the situation as you wish. You can find more details in the following link http://developer.android.com/training/basics/network-ops/managing.html
You can check by this method that wifi is interrupted or not?
ConnectivityManager networkManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = networkManager.getActiveNetworkInfo();
NetworkInfo wifi = networkManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifi.isAvailable() && wifi.isConnected()) {
return true;
}else {
return false;
}
You can add broadcast receiver to lsten for network changes, you can add this method in onReceive() method, and check it, If network chanes, you will receive notification on onReceive() and then you can handle whatever you want as your wish

Categories

Resources