How to check if the Internet connection (Wifi/Mobile data) is ENABLED? - java

How to check if the internet connection is Enabled in Android? Like if the LOCATION SERVICE is disabled we use the technique
Location myLocation = locationmanager.getLastKnownLocation(provider);
if(myLocation == null){
Show the AlertDialog.
}else{
do this.
}
Like this, how do i check if the Internet connection is Enabled/Disabled.

You can use the following method:
ConnectivityManager conectivtyManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conectivtyManager.getActiveNetworkInfo() != null
&& conectivtyManager.getActiveNetworkInfo().isAvailable()
&& conectivtyManager.getActiveNetworkInfo().isConnected()) {
isConnected = true;
} else {
isConnected= false;
}
Hope it helps!

For wifi:
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
connected = networkInfo != null && networkInfo.isConnected();
For Mobile:
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
connected = networkInfo != null && networkInfo.isConnected();

Related

Better way to implement network thread than using a loader or AsyncTask

The Loader class is depreciated and while overriding the methods for network call the callback function are not performing as aspected.
I've implemented the "implements LoaderCallbacks>"
ConnectionManager connMgr =(ConnectionManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(CUSTOM_JSON_LOADER_ID, null, this);
} else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}

How can I monitor for changes to mobile data being enabled on Android?

I have successfully used the answer to this question to perform a one off check if mobile data is enabled, but I would like to receive a notification of such change, for example when a user goes to this screen:
Is this possible?
You can use OnNetworkActiveListener to monitor activation of network data. The ConnectivityManager class can give you infos on the currently active network connection. It would go like this :
ConnectivityManager cm = getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfos networkInfos = cm.getActiveNetworkInfo();
if(networkInfos.isConnected()){
//Do something
} else {
//Do something else
}
Hope it helps.
public static boolean isNetworkOn(Context context, int networkType) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= 21) {
final Network[] networks = connectivityManager.getAllNetworks();
for (Network network : networks) {
final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.getType() == networkType && networkInfo.isConnectedOrConnecting()) {
return true;
}
}
}
else {
#SuppressWarnings("deprecation") final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(networkType);
if (networkInfo.isConnectedOrConnecting()) {
return true;
}
}
return false;
}

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.

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.

how to check wifi or 3g network is available on android device

Here, my android device supports both wifi and 3g. At particular time which network is available on this device. Because my requirement is when 3g is available I have to upload small amount of data. when wifi is available entire data have to upload. So, I have to check connection is wifi or 3g. Please help me. Thanks in advance.
I use this:
/**
* Checks if we have a valid Internet Connection on the device.
* #param ctx
* #return True if device has internet
*
* Code from: http://www.androidsnippets.org/snippets/131/
*/
public static boolean haveInternet(Context ctx) {
NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return false;
}
return true;
}
You also need
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in AndroidMainfest.xml
To get the network type you can use this code snippet:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
State mobile = conMan.getNetworkInfo(0).getState();
//wifi
State wifi = conMan.getNetworkInfo(1).getState();
and then use it like that:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}
To get the type of the mobile network I would try TelephonyManager#getNetworkType or NetworkInfo#getSubtypeName
You need to add below permission in android manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
After that you can use below functions to check wifi or mobile network is connected or not
public static boolean isWifiConnected(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return ((netInfo != null) && netInfo.isConnected());
}
public static boolean isMobileConnected(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return ((netInfo != null) && netInfo.isConnected());
}
Some references from developer.android.com are:
https://developer.android.com/reference/android/net/ConnectivityManager.html
https://developer.android.com/reference/android/net/NetworkInfo.html
https://developer.android.com/reference/android/net/ConnectivityManager.html#getActiveNetworkInfo()
First get a reference to the ConnectivityManager and then check the Wifi and 3G status of the device.
You'll need the ACCESS_NETWORK_STATE permission to use this service.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mWifi.isAvailable() == true) {
return "Connected to WiFi";
} else if (mMobile.isAvailable() == true) {
return "Connected to Mobile Network";
} else return "No internet Connection"
You can use this method to check whether your internet connection is 2G, 3G or 4G:
public String getNetworkClass(Context context) {
TelephonyManager mTelephonyManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
int networkType = mTelephonyManager.getNetworkType();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return "2G";
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return "3G";
case TelephonyManager.NETWORK_TYPE_LTE:
return "4G";
default:
return "Unknown";
}
}
And using following method you can check if internet is available or not, and get whether you are accessing the internet via a mobile network or WiFi:
public String getNetworkType(Context context){
String networkType = null;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
networkType = "WiFi";
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
networkType = "Mobile";
}
} else {
// not connected to the internet
}
return networkType;
}

Categories

Resources