Wait for network connection - java

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.

Related

Android: How to check if device is connected to another device via WiFi - Direct?

I was wondering if there is a way, similar to checking if there is a WiFi connection established.
ConnectivityManager connManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
But with WiFi p2p?
My application connects to a sensor via WiFi-Direct. If the user has not connected to the sensor, a textView should appear saying "You are not connected to a sensor". Currently this only works if the user starts the WiFi Direct activity, which registers a Broadcast Receiver which checks if the device is connected to something via WiFi p2p. But I want to know this without having to start my WiFi Direct activity. Is there a way to do this?
private void checkWifiOnAndConnected() {
WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
if (wifiMgr.isWifiEnabled()) { // WiFi adapter is ON
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
connected_wifi=wifiInfo.getSSID();
}
else {
// Utill.showCenteredToast(getActivity(), getResources().getString(R.string.str_wifi_on));
}
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

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

NetworkChangeReceiver's onReceive method is called multiple times when 3G and WIFI are enable at same time

I'm developing an android application and I have the next problem:
I implemented Broadcast receiver for connectivity change and the method onReceive seems to be called 4 times in a row when 3G and Wifi are enabled at the same time.
So my question is:
Is there a way listen only for internet connection, not for network change?
Or is there any way for the method onReceive to be called only once when 3G and Wifi are enable at the same time?
Here is my code:
public class NetworkChangeReceiver extends BroadcastReceiver {
public static final String TAG = "NetworkMonitoring";
#Override
public void onReceive(Context context, Intent intent) {
if (isOnline(context)) {
Log.v(TAG, "Connected!");
// update(context);
} else {
Log.v(TAG, "Not connected!");
// stopUpdate(context);
}
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
return true;
return false;
}
}
In the Android Manifest:
<receiver android:name="xxxxx.xxxxx.xxxxx.NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Here is the log:
05-06 16:24:05.985: V/NetworkMonitoring(569): Connected!
05-06 16:24:10.250: V/NetworkMonitoring(569): Connected!
05-06 16:24:10.720: V/NetworkMonitoring(569): Connected!
05-06 16:24:11.031: V/NetworkMonitoring(569): Connected!
(Notice the time!)
I had the same problem with the same type of broadcast receiver.
Searched a little and found a workaround.
BroadcastReceiver receives multiple identical messages for one event
Edit:
The workaround is to use a flag that tells you when is the first time onReceive is being invoked.
public class ConnectionChangeReceiver extends BroadcastReceiver {
private static boolean firstConnect = true;
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null) {
if(firstConnect) {
// do subroutines here
firstConnect = false;
}
}
else {
firstConnect= true;
}
}
}
Hope it helps.

find out whether wi-fi is enabled and connected

I've found this answer on so many answers here on SO :
I'm checking whether user has wi-fi enabled and is connected when he chooses the spinner option(drop down menu).
private static boolean isConnected(Context context, AdapterView<?> parent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
return networkInfo == null ? false : networkInfo.isConnected();
}
It's not working for me, I must have forgotten some permissions in Manifest what else am I
missing?
Or is it better that I use WifiManager does anyone have example for that ?
Make sure you are using the permission android.permission.ACCESS_WIFI_STATE in your Manifest and android.permission.ACCESS_NETWORK_STATE if you want to read the cellular network state.

wait until wifi connected on android

I have a small program that trying to connect to a wifi network.
It enables the wifi on the device then if it's the first time that is connect to the certain networkss It loads the device wifi in order to select and add the password for connection.
Until I add the password in order to connect the program should not be finished.
How can I add something to wait until I get from the wifi manager that is connected?
I try sleep but it freeze the application and am not getting the wifi pop up menu to connect?
are there any other ways?
I have found the solution for your problem a month ago, just use Thread put method isConnected() in it. In this case, I use WifiExplorerActivity to display all wifi network and allow user connect to it.
Thread t = new Thread() {
#Override
public void run() {
try {
//check if connected!
while (!isConnected(WifiExplorerActivity.this)) {
//Wait to connect
Thread.sleep(1000);
}
Intent i = new Intent(WifiExplorerActivity.this, MainActivity.class);
startActivity(i);
} catch (Exception e) {
}
}
};
t.start();
And this is function to check wifi has connected or not:
public static boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getActiveNetworkInfo();
}
return networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED;
}
Finally, make sure your Androidmanifest.xml look like this:
<activity android:name=".WifiExplorerActivity" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</activity>
Also, you can use ProgressDialog to wait connect. See http://developer.android.com/guide/topics/ui/dialogs.html

Categories

Resources