Actually i had used the following code to check the wifi is active or not (its working fine).
I just want to confirm that can i use the same code to check the 3G active state:
public boolean checkwifi()
{
ConnectivityManager connec = (ConnectivityManager) this.getSystemService(this.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Here if condition check for wifi and mobile network is available or not.
// If anyone of them is available or connected then it will return true, otherwise false;
if (wifi.isConnected()) {
return true;
}
else if (mobile.isConnected()) {
return true;
}
return false;
}
to check if your connection(WIFI or Mobile ) is On or Off , try this :
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTING ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTING) {
//we are connected to a network
connected = true;
}
else
connected = false;
Yes - this code should work. I've got an extra bit of functionality you may want to implement:
public static boolean isOnline(Context context) {
//ConnectivityManager is used to check available network(s)
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
This does the same as your code - it will tell you if you are online via any method (3G or WiFi), but it's a bit more concise.
** EDIT **
Here's the source for that method - it will return null if no active network connection or will return a NetworkInfo object for a current connection:
/**
* Return NetworkInfo for the active (i.e., connected) network interface.
* It is assumed that at most one network is active at a time. If more
* than one is active, it is indeterminate which will be returned.
* #return the info for the active network, or {#code null} if none is active
*/
public NetworkInfo getActiveNetworkInfo() {
enforceAccessPermission();
for (NetworkStateTracker t : mNetTrackers) {
NetworkInfo info = t.getNetworkInfo();
if (info.isConnected()) {
return info;
}
}
return null;
}
Related
For my app, I need to make sure the user is connected to wifi before contact with the server. I have found two methods to do so, but I am not sure if one suffices.
First I am adding this:
WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
.getSystemService(WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
buildAlertNoWifi();
showProgressDialog(false, "");
return;
}
And then I am doing this:
ConnectivityManager cm = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
Toast.makeText(getContext(), "Make sure you connect to wifi.", Toast.LENGTH_LONG).show();
return;
}
} else {
Toast.makeText(getContext(), "Make sure you connect to wifi.", Toast.LENGTH_LONG).show();
return;
}
So I was wondering if wifiManager.isWifiEnabled() returns whether the device is connected to a wifi or just has wifi turned on. And if so, is it enough to use it alone?
I believe WifiManager.isWifiEnabled() only checks if device's wifi is turned on. Please use NetworkInfo.isConnected() or NetworkInfo.isConnectedOrConnecting() to check if it's connected to any network.
Best Practice
public boolean isWifiConnected() {
NetworkInfo net = getActiveNetworkInfo();
return (isConnected(net) && net.getType() == TYPE_WIFI);
}
private NetworkInfo getActiveNetworkInfo() {
ConnectivityManager connManager = (ConnectivityManager)
Application.getContext()
.getSystemService(Application.CONNECTIVITY_SERVICE);
return connManager.getActiveNetworkInfo();
}
I believe this should work,
public boolean isWifiConnected()
{
ConnectivityManager cm = (ConnectivityManager)this.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
return (cm != null) && (cm.getActiveNetworkInfo() != null) &&
(cm.getActiveNetworkInfo().getType() == 1);
}
This code works:
public static boolean isConnected()
{
ConnectivityManager cm = (ConnectivityManager)App.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null) {
if (ni.getType() == ConnectivityManager.TYPE_WIFI)
if (ni.isConnected())
return true;
if (ni.getType() == ConnectivityManager.TYPE_MOBILE)
if (ni.isConnected())
return true;
if (ni.getType() == ConnectivityManager.TYPE_ETHERNET)
if (ni.isConnected())
return true;
}
return false; //none of connections available
}
The question is: do we also have to check TYPE_MOBILE_DUN, TYPE_WIMAX and TYPE_VPN?
Can a device be connected to the Internet over Bluetooth?
Just one comment. Think what do you need and remember to be connected to a wifi router doesn't mean you have internet connection or that you are able to reach any point of interest like a backend server.
If your app needs to access a service to work, may be the best way it is to check if you can reach it in an early stage through an async call and only proceed if you could validate that connection.
Try to make a simple GET request to http://www.google.com. If your response code is 200 or 400 Then the internet connection exists.
protected static boolean hasInternetAccess()
{
try
{
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application:1");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30);
urlc.connect();
// http://www.w3.org/Protocols/HTTP/HTRESP.html
if (urlc.getResponseCode() == 200 || urlc.getResponseCode() > 400)
{
// Requested site is available
return true;
}
}
catch (Exception ex)
{
// Error while trying to connect
return false;
}
return false;
}
For more info, refer to: The perfect function to check Android internet connectivity including bluetooth pan
This is all I use:
public static boolean isOffline() {
ConnectivityManager cm = (ConnectivityManager) BigOvenApplication.getInstance()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo == null || !netInfo.isConnected();
}
I don't think you need anything more than that.
Just call the method isConnectedToNetwork to check whether it has connection or not. Write this method in a common class file. Thereby you can use simple methodcall where ever you need.
public static boolean isConnectedToNetwork(Context thisActivity) {
ConnectivityManager connMgr = (ConnectivityManager) thisActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
return true;
}
return false;
}
Check before you start the operation.
//thisActivity means getActivity() for fragments
if (isConnectedToNetwork(thisActivity)) {
// your operation code follows
} else {
//show alert box that there is no internet connection
}
I want to check if a particular device has hardware support for 4G networks.
I will elaborate the issue...
In the application we have a settings page where user can make selection and allow application to run only in selected networks.
Eg. User can select that app will run only in WiFi network or only in 3G network etc.
There are CheckBox preferences for all networks WiFi, 2G, 3G 4G etc.
Now if the device doesn't have the support for 4G network, I want to hide the 4G selection checkbox.
All the remaining functionality is complete. I am struck on just this issue that how to detect if device support 4G or not?
Please note that I want to detect hardware support for 4G on the device and NOT the 4G connection is connected or so.
Any help is greatly appreciated.
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = cm.getAllNetworkInfo();
for(int i=0; i <info.length; i++){
Log.i("netinfo"+i, info[i].getType()+"");
Log.i("netinfo"+i, info[i].getTypeName());
Log.i("netinfo"+i, info[i].getSubtype()+"");
Log.i("netinfo"+i, info[i].getSubtypeName());
}
Use this piece of code and get all available options on the device. I think you should be able to get all capabilities of the device.
and network type info is present in http://developer.android.com/reference/android/telephony/TelephonyManager.html.
I think network types added from API level 11 are for 4g. Check it yourself.
This might work. It should check for WiMax 4g:
private boolean is4gavailable() {
ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileInfo = connec.getNetworkInfo(0);
NetworkInfo wifiInfo = connec.getNetworkInfo(1);
NetworkInfo wimaxInfo = connec.getNetworkInfo(6);
if (wimaxInfo!=null) {
return mobileInfo.isConnectedOrConnecting() || wifiInfo.isConnectedOrConnecting() || wimaxInfo.isConnectedOrConnecting();
}
else {
return mobileInfo.isConnectedOrConnecting() || wifiInfo.isConnectedOrConnecting();
}
}
Try looking at this for a little more clarification.
Context context = MainActivity.this;
public synchronized static boolean isNetAvailable(Context context){
boolean isNetAvailable=false;
if ( context != null ){
ConnectivityManager mgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if ( mgr != null )
{
boolean mobileNetwork = false;
boolean wifiNetwork = false;
boolean wiMaxNetwork = false;
boolean mobileNetworkConnecetd = false;
boolean wifiNetworkConnecetd = false;
boolean wiMaxNetworkConnected = false;
NetworkInfo mobileInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo wiMaxInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
if ( mobileInfo != null )
mobileNetwork = mobileInfo.isAvailable();
if ( wifiInfo != null )
wifiNetwork = wifiInfo.isAvailable();
if(wiMaxInfo != null)
wiMaxNetwork = wiMaxInfo.isAvailable();
if(wifiNetwork == true || mobileNetwork == true || wiMaxNetwork == true){
mobileNetworkConnecetd = mobileInfo.isConnectedOrConnecting();
wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
wiMaxNetworkConnected = wiMaxInfo.isConnectedOrConnecting();
}
isNetAvailable = ( mobileNetworkConnecetd || wifiNetworkConnecetd || wiMaxNetworkConnected );
}
}
return isNetAvailable;
}
Check for value of isNetAvailable is true in all the 3 cases this works for me, wish work for u too
Note : 4G availability will be introduces API level 8 onwards.
I have to connect my app with server using either wifi (if it is available),
or gprs (if wifi is not available).
Here is my code to check the connection availability
public static final boolean isConnectionAvailable(Activity a)
{
ConnectivityManager cm = (ConnectivityManager)a.getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = cm.getNetworkInfo(0).getState();
State wifi = cm.getNetworkInfo(1).getState();
if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
return true;
}
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
return true;
}
return false;
}
Is this a correct way? Can anyone suggest me a better way?
The following very similar approach works, but has the added advantage of not caring what the underlying medium, since it looks as though there is support for more than just WiFi. Maybe these are also covered by mobile, but the docs aren't super clear:
// added as an instance method to an Activity
boolean isNetworkConnectionAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info == null) return false;
State network = info.getState();
return (network == NetworkInfo.State.CONNECTED || network == NetworkInfo.State.CONNECTING);
}
Network Availability Check :
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Or you could use some kotlin implementation
fun Context.isNetworkAvailable(): Boolean {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
return activeNetwork?.isConnectedOrConnecting == true
}
I am building an Android app and I use the code below to detect whether there is a network connection. It works well and detects both mobile and WIFI networks.
My problem is how to detect an actual internet connection. The code below returns true when connected to WIFI however the WIFI might not necessarily be connected to the Internet.
The code
protected boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
}
else {
return false;
}
} //end checkInterneConnection method
Thanks for your time.
Mel
You should try to reach an internet adress. Therefor you should check the InetAdress class and the method isReachable: http://developer.android.com/reference/java/net/InetAddress.html#isReachable%28int%29
This piece of code will check whether your device Internet conecction, If the signal is Poor it will show a Toast other wise not,
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = conMan.getActiveNetworkInfo();
if(Info == null){
Toast.makeText(RegisterActivity.this,"Network Connection Failed! ", Toast.LENGTH_SHORT).show();
}
You can try ping http://google.com or doing something like this to confirm it's ok to visit internet.
You should try this:
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)
m_context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() ==
NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
And to check only wifi is simpler:
private boolean isWifiConnected() {
int WIFI_STATE = wifi.getWifiState();
if(WIFI_STATE == WifiManager.WIFI_STATE_ENABLED)
return true;
return false;
}
This code will really test the internet connection:
public static boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("google.com");
return address.isReachable(2000); //This really tests if the ip, given by the url, is reachable
//return !address.equals(""); //This just tests if the IP is available but it could be taken in a previous request when internet was available
} catch (Exception e) {
Log.d("Internet check", "Unable to reach the url: "+url);
}
return false;
}