Broadcast receiver for checking internet connection in android app












200















I am developing an android broadcast receiver for checking internet connection.



The problem is that my broadcast receiver is being called two times. I want it to get called only when the network is available. If it is unavailable, I don't want notified.



This is the broadcast receiver



public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if (wifi.isAvailable() || mobile.isAvailable()) {
// Do something

Log.d("Network Available ", "Flag No 1");
}
}
}


This is the manifest.xml



<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiverforinternetconnection"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
</application>

</manifest>









share|improve this question

























  • Please check stackoverflow.com/questions/10273614/…

    – Adrian
    Mar 29 '13 at 7:08
















200















I am developing an android broadcast receiver for checking internet connection.



The problem is that my broadcast receiver is being called two times. I want it to get called only when the network is available. If it is unavailable, I don't want notified.



This is the broadcast receiver



public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if (wifi.isAvailable() || mobile.isAvailable()) {
// Do something

Log.d("Network Available ", "Flag No 1");
}
}
}


This is the manifest.xml



<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiverforinternetconnection"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
</application>

</manifest>









share|improve this question

























  • Please check stackoverflow.com/questions/10273614/…

    – Adrian
    Mar 29 '13 at 7:08














200












200








200


87






I am developing an android broadcast receiver for checking internet connection.



The problem is that my broadcast receiver is being called two times. I want it to get called only when the network is available. If it is unavailable, I don't want notified.



This is the broadcast receiver



public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if (wifi.isAvailable() || mobile.isAvailable()) {
// Do something

Log.d("Network Available ", "Flag No 1");
}
}
}


This is the manifest.xml



<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiverforinternetconnection"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
</application>

</manifest>









share|improve this question
















I am developing an android broadcast receiver for checking internet connection.



The problem is that my broadcast receiver is being called two times. I want it to get called only when the network is available. If it is unavailable, I don't want notified.



This is the broadcast receiver



public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if (wifi.isAvailable() || mobile.isAvailable()) {
// Do something

Log.d("Network Available ", "Flag No 1");
}
}
}


This is the manifest.xml



<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiverforinternetconnection"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
</application>

</manifest>






java android broadcastreceiver android-wifi android-networking






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 26 '16 at 4:07









Gary

7,447123562




7,447123562










asked Mar 29 '13 at 6:54









Nikhil AgrawalNikhil Agrawal

17k1673109




17k1673109













  • Please check stackoverflow.com/questions/10273614/…

    – Adrian
    Mar 29 '13 at 7:08



















  • Please check stackoverflow.com/questions/10273614/…

    – Adrian
    Mar 29 '13 at 7:08

















Please check stackoverflow.com/questions/10273614/…

– Adrian
Mar 29 '13 at 7:08





Please check stackoverflow.com/questions/10273614/…

– Adrian
Mar 29 '13 at 7:08












15 Answers
15






active

oldest

votes


















222














Answer to your first question: Your broadcast receiver is being called two times because



You have added two <intent-filter>




  1. Change in network connection :
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />


  2. Change in WiFi state:
    <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />



Just use one:
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />.



It will respond to only one action instead of two. See here for more information.



Answer to your second question (you want receiver to call only one time if internet connection available):



Your code is perfect; you notify only when internet is available.



UPDATE



You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.



public boolean isOnline(Context context) {

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
}





share|improve this answer


























  • No my second Query is I want notification when only the network is available but if the phone is loosing the network then to it is notifying me.

    – Nikhil Agrawal
    Mar 30 '13 at 5:58






  • 7





    same here. I just have <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> registered but my receiver still get called twice. It is not really big problem but I would like to know why.

    – Yeung
    May 8 '13 at 7:17






  • 1





    I am familiar with all of this , but I have doubts. I did some tests and found out that these broadcast receivers detect if your wifi / phone radio goes ON or OFF, or simply, if your device has an IP address. The problem comes when for example my phone is connected to a WiFi access point but such access point has no Internet. The code/phone tell me it a data connection regardless if the access point is providing it with Internet or Not. Does anybody know how to create a real Data-Internet listener, not just a WiFI/On/Off Listener?

    – Josh
    Jul 15 '14 at 10:07








  • 4





    @JosueGalindo onReceiving, you can use this code to know if device is connected to internet pastebin.com/dV3pJjkm

    – Seshu Vinay
    Jul 18 '14 at 6:47











  • does this really check if the internet is available? or if it is just connected to a network where internet SHOULD be available.. if it is connected to a wifi network for instance that doesn't have an internet connection won't this still return true?

    – erik
    Apr 24 '15 at 12:57



















70





+25









public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

if(checkInternet(context))
{
Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
}

}

boolean checkInternet(Context context) {
ServiceManager serviceManager = new ServiceManager(context);
if (serviceManager.isNetworkAvailable()) {
return true;
} else {
return false;
}
}

}


ServiceManager.java



public class ServiceManager {

Context context;

public ServiceManager(Context base) {
context = base;
}

public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}


permissions:



 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />





share|improve this answer





















  • 1





    for me the problem was receiver gets called twice on network change?

    – manivannan
    Sep 30 '14 at 7:06






  • 9





    why would you use a ContextWrapper? Want to understand

    – Darpan
    Jun 25 '15 at 7:28






  • 1





    me also getting @manivannan problem... reciever calling twice on network change... is there any solution for that

    – venkat
    Jun 22 '16 at 5:17











  • No need to extend ServiceManager with ContextWrapper.

    – Yogesh Seralia
    Jun 30 '16 at 11:16











  • thx for reminding about ACCESS_NETWORK_STATE

    – Defuera
    Sep 1 '16 at 20:59



















38














Checking internet status every time using Broadcast Receiver:



internet status implementation



Full source code available on Google Drive.



AndroidManifest.xml



<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>


BroadcastReciever



package com.keshav.networkchangereceiverexample.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import static com.keshav.networkchangereceiverexample.MainActivity.dialog;

public class NetworkChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
try
{
if (isOnline(context)) {
dialog(true);
Log.e("keshav", "Online Connect Intenet ");
} else {
dialog(false);
Log.e("keshav", "Conectivity Failure !!! ");
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}

private boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}


MainActivity.java



package com.keshav.networkchangereceiverexample;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver;

public class MainActivity extends AppCompatActivity {

private BroadcastReceiver mNetworkReceiver;
static TextView tv_check_connection;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
mNetworkReceiver = new NetworkChangeReceiver();
registerNetworkBroadcastForNougat();

}

public static void dialog(boolean value){

if(value){
tv_check_connection.setText("We are back !!!");
tv_check_connection.setBackgroundColor(Color.GREEN);
tv_check_connection.setTextColor(Color.WHITE);

Handler handler = new Handler();
Runnable delayrunnable = new Runnable() {
@Override
public void run() {
tv_check_connection.setVisibility(View.GONE);
}
};
handler.postDelayed(delayrunnable, 3000);
}else {
tv_check_connection.setVisibility(View.VISIBLE);
tv_check_connection.setText("Could not Connect to internet");
tv_check_connection.setBackgroundColor(Color.RED);
tv_check_connection.setTextColor(Color.WHITE);
}
}


private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}

protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}

@Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
}


activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.keshav.networkchangereceiverexample.MainActivity">

<TextView
android:id="@+id/tv_check_connection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connection establised !"
android:padding="25dp"
app:layout_constraintBottom_toBottomOf="parent"
android:gravity="center"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>





share|improve this answer


























  • Its Very usefull same as youtube every time check online ,offline

    – Keshav Gera
    Aug 22 '17 at 7:33











  • Thanks for your great post. Why did you add this: Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) in registerNetworkBroadcastForNougat? The manifest is not working in android N and Up and M shoud be fine

    – Amir
    Aug 26 '17 at 2:45











  • Amir mind make up to Android N therefore i use

    – Keshav Gera
    Sep 12 '17 at 12:26








  • 3





    duplicate code at registerNetworkBroadcastForNougat()

    – lenhuy2106
    Jan 18 '18 at 21:38











  • shouldnt there be a else in this code segment ? 'if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); }'

    – Siddharth
    May 30 '18 at 12:29



















25














Use this method to check the network state:



private void checkInternetConnection() {

if (br == null) {

br = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {

Bundle extras = intent.getExtras();

NetworkInfo info = (NetworkInfo) extras
.getParcelable("networkInfo");

State state = info.getState();
Log.d("TEST Internet", info.toString() + " "
+ state.toString());

if (state == State.CONNECTED) {
Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();

} else {
Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
}

}
};

final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver((BroadcastReceiver) br, intentFilter);
}
}


remember to unregister service in onDestroy.



Cheers!!






share|improve this answer































    9














    public static boolean isNetworkAvailable(Context context) {
    boolean isMobile = false, isWifi = false;

    NetworkInfo infoAvailableNetworks = getConnectivityManagerInstance(
    context).getAllNetworkInfo();

    if (infoAvailableNetworks != null) {
    for (NetworkInfo network : infoAvailableNetworks) {

    if (network.getType() == ConnectivityManager.TYPE_WIFI) {
    if (network.isConnected() && network.isAvailable())
    isWifi = true;
    }
    if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
    if (network.isConnected() && network.isAvailable())
    isMobile = true;
    }
    }
    }

    return isMobile || isWifi;
    }

    /* You can write such method somewhere in utility class and call it NetworkChangeReceiver like below */
    public class NetworkChangedReceiver extends BroadcastReceiver
    {
    @Override
    public void onReceive(Context context, Intent intent) {

    if (isNetworkAvailable(context))
    {
    Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();


    }
    }
    }


    This above broadcast receiver will be called only when Network state change to connected and not on disconnected.






    share|improve this answer

































      7














      Try with this



      public class ConnectionBroadcastReceiver extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {


      if (<Check internet connection available >) {
      Toast.makeText(context, "connect to the internet", Toast.LENGTH_LONG).show();

      /*upload background upload service*/
      Intent serviceIntent = new Intent(context,<your service class>);
      context.startService(serviceIntent);


      }else{
      Toast.makeText(context, "Connection faild", Toast.LENGTH_LONG).show();

      }




      }
      }


      This is the broadcast Receiver. soon as internet connection trigger this will loaded






      share|improve this answer


























      • And how do you register this receiver? What intent filter?

        – Stealth Rabbi
        Jan 27 '16 at 19:11



















      7














      I know this thread is old and fully answered but I feel that the following might help some people.



      The code in the body of the question contains a bug which no one here addressed.
      @Nikhil is checking whether the wifi/mobile is available and not if it's connected.



      The fix is here:



      @Override
      public void onReceive(final Context context, final Intent intent) {
      final ConnectivityManager connMgr = (ConnectivityManager) context
      .getSystemService(Context.CONNECTIVITY_SERVICE);

      final android.net.NetworkInfo wifi = connMgr
      .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

      final android.net.NetworkInfo mobile = connMgr
      .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

      if (wifi.isConnected() || mobile.isConnected()) {
      // do stuff
      }
      }





      share|improve this answer


























      • Yes, I just want to suggest the same, wifi.isConnected() fix

        – Erich García
        Sep 17 '17 at 3:27



















      6














      manifest:



      <receiver android:name=".your.namepackage.here.ConnectivityReceiver">
      <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
      </intent-filter>
      </receiver>


      class for receiver:



      public class ConnectivityReceiver extends BroadcastReceiver{

      @Override
      public void onReceive(Context context, Intent intent) {
      final String action = intent.getAction();
      switch (action) {
      case ConnectivityManager.CONNECTIVITY_ACTION:
      DebugUtils.logDebug("BROADCAST", "network change");
      if(NetworkUtils.isConnect()){
      //do action here
      }
      break;
      }
      }
      }


      and classs utils like example:



      public class NetworkUtils {

      public static boolean isConnect() {
      ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      Network netArray = connectivityManager.getAllNetworks();
      NetworkInfo netInfo;
      for (Network net : netArray) {
      netInfo = connectivityManager.getNetworkInfo(net);
      if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
      //if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
      Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
      return true;
      }
      }
      } else {
      if (connectivityManager != null) {
      @SuppressWarnings("deprecation")
      NetworkInfo netInfoArray = connectivityManager.getAllNetworkInfo();
      if (netInfoArray != null) {
      for (NetworkInfo netInfo : netInfoArray) {
      if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
      //if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
      Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
      return true;
      }
      }
      }
      }
      }
      return false;
      }
      }





      share|improve this answer

































        5














        CONNECTIVITY_ACTION docs:




        Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.







        share|improve this answer

































          4














          just for someone else who wanna register a broadcast dynamicly:



          BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
          if (checkWifiConnect()) {
          Log.d(TAG, "wifi has connected");
          // TODO
          }
          }
          };

          private void registerWifiReceiver() {
          IntentFilter filter = new IntentFilter();
          filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
          filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
          filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
          mContext.registerReceiver(mWifiReceiver, filter);
          }

          private void unregisterWifiReceiver() {
          mContext.unregisterReceiver(mWifiReceiver);
          }

          private boolean checkWifiConnect() {
          ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo networkInfo = manager.getActiveNetworkInfo();
          if (networkInfo != null
          && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
          && networkInfo.isConnected()) {
          return true;
          }
          return false;
          }





          share|improve this answer































            3














            public class AsyncCheckInternet extends AsyncTask<String, Void, Boolean> {

            public static final int TIME_OUT = 10 * 1000;

            private OnCallBack listener;

            public interface OnCallBack {

            public void onBack(Boolean value);
            }

            public AsyncCheckInternet(OnCallBack listener) {
            this.listener = listener;
            }

            @Override
            protected void onPreExecute() {
            }

            @Override
            protected Boolean doInBackground(String... params) {

            ConnectivityManager connectivityManager = (ConnectivityManager) General.context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

            if ((networkInfo != null && networkInfo.isConnected())
            && ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) || (networkInfo
            .getType() == ConnectivityManager.TYPE_MOBILE))) {
            HttpURLConnection urlc;
            try {
            urlc = (HttpURLConnection) (new URL("http://www.google.com")
            .openConnection());
            urlc.setConnectTimeout(TIME_OUT);
            urlc.connect();
            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return true;
            } else {
            return false;
            }
            } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;

            } catch (IOException e) {
            e.printStackTrace();
            return false;

            }
            } else {
            return false;
            }
            }

            @Override
            protected void onPostExecute(Boolean result) {
            if (listener != null) {
            listener.onBack(result);
            }
            }


            }






            share|improve this answer
























            • AsynTasks should be used for something really small. You should use Service instead.

              – TheLibrarian
              Aug 28 '17 at 14:35



















            3














            Add a broadcast receiver which can listen to network connectivity change. Then check wether device is connected to internet or not using ConnectivityManager. Refer to this post or video for detailed understanding. Below is the code:



            public class NetworkStateChangeReceiver extends BroadcastReceiver {
            public static final String NETWORK_AVAILABLE_ACTION = "com.ajit.singh.NetworkAvailable";
            public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";

            @Override
            public void onReceive(Context context, Intent intent) {
            Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
            networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
            LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
            }

            private boolean isConnectedToInternet(Context context) {
            try {
            if (context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
            }
            return false;
            } catch (Exception e) {
            Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
            return false;
            }
            }
            }


            I wrote this receiver to show a notification on the Screen, that's why you see a local broadcast with the network status. Here is the code to show the notification.



            public class MainActivity extends AppCompatActivity {

            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
            LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
            boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
            String networkStatus = isNetworkAvailable ? "connected" : "disconnected";

            Snackbar.make(findViewById(R.id.activity_main), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
            }
            }, intentFilter);
            }
            }


            Activity listens to the intent broadcasted by the network receiver and shows the notification on the screen.






            share|improve this answer































              2














              Here's a comfortable way to do it for activity, fragment or context. It will also auto-unregister if you do it for activity/fragment (in onDestroy), if you wish:



              abstract class ConnectionBroadcastReceiver : BroadcastReceiver() {
              companion object {
              @JvmStatic
              fun registerWithoutAutoUnregister(context: Context, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
              context.registerReceiver(connectionBroadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
              }

              @JvmStatic
              fun registerToFragmentAndAutoUnregister(context: Context, fragment: Fragment, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
              val applicationContext = context.applicationContext
              registerWithoutAutoUnregister(applicationContext, connectionBroadcastReceiver)
              fragment.lifecycle.addObserver(object : LifecycleObserver {
              @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
              fun onDestroy() {
              applicationContext.unregisterReceiver(connectionBroadcastReceiver)
              }
              })
              }

              @JvmStatic
              fun registerToActivityAndAutoUnregister(activity: AppCompatActivity, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
              registerWithoutAutoUnregister(activity, connectionBroadcastReceiver)
              activity.lifecycle.addObserver(object : LifecycleObserver {
              @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
              fun onDestroy() {
              activity.unregisterReceiver(connectionBroadcastReceiver)
              }
              })
              }

              @JvmStatic
              fun hasInternetConnection(context: Context): Boolean {
              val info = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
              return !(info == null || !info.isConnectedOrConnecting)
              }
              }

              override fun onReceive(context: Context, intent: Intent) {
              val hasConnection = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
              // Log.d("AppLog", "conenctivity changed. hasConnection? $hasConnection")
              onConnectionChanged(hasConnection)
              }

              abstract fun onConnectionChanged(hasConnection: Boolean)
              }


              Usage in fragment:



                  ConnectionBroadcastReceiver.registerToFragmentAndAutoUnregister(activity!!, this, object : ConnectionBroadcastReceiver() {
              override fun onConnectionChanged(hasConnection: Boolean) {
              // Log.d("AppLog", "onConnectionChanged:" + hasConnection)
              }
              })





              share|improve this answer

































                1














                Broadcast receiver code to check internet connectivity change:



                public class BroadCastDetecter extends BroadcastReceiver {
                public static boolean internet_status = false;
                public static void checkInternetConenction(Context context) {
                internet_status = false;
                ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (check != null) {
                NetworkInfo info = check.getAllNetworkInfo();
                if (info != null)
                for (int i = 0; i < info.length; i++)
                {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                internet_status = true;
                }
                }
                if(internet_status)
                {
                //do what you want to if internet connection is available
                }
                }
                }

                @Override
                public void onReceive(Context context, Intent intent)
                {
                try {
                checkInternetConenction(context);
                }catch(Exception e){

                }
                }
                }


                add this in manifest file:



                 <receiver android:name=".BroadCastDetecter">
                <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                </intent-filter>
                </receiver>





                share|improve this answer































                  -1














                  First of all we will make a class that will check the connectivity of the network state. So lets create a class :



                  public class AppStatus {
                  private static AppStatus instance = new AppStatus();
                  static Context context;
                  ConnectivityManager connectivityManager;
                  NetworkInfo wifiInfo, mobileInfo;
                  boolean connected = false;

                  public static AppStatus getInstance(Context ctx) {
                  context = ctx.getApplicationContext();
                  return instance;
                  }

                  public boolean isOnline() {
                  try {
                  connectivityManager = (ConnectivityManager) context
                  .getSystemService(Context.CONNECTIVITY_SERVICE);

                  NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                  connected = networkInfo != null && networkInfo.isAvailable() &&
                  networkInfo.isConnected();
                  return connected;


                  } catch (Exception e) {
                  System.out.println("CheckConnectivity Exception: " + e.getMessage());
                  Log.v("connectivity", e.toString());
                  }
                  return connected;
                  }
                  }


                  Now Make a new Broadcast receiver class :



                  public class ConnectivityReceiver extends BroadcastReceiver {
                  @Override
                  public void onReceive(Context context, Intent intent) {
                  if (AppStatus.getInstance(context).isOnline()) {

                  Intent intent1=new Intent(context,DisplayAct.class);
                  intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                  context.startActivity(intent1);




                  } else {

                  Toast.makeText(context, "Please !! Make your network ON", Toast.LENGTH_SHORT).show();

                  }
                  }
                  }


                  and Now register your broadcast receiver on manifest:



                  <receiver android:name=".ConnectivityReceiver">
                  <intent-filter>
                  <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                  </intent-filter>
                  </receiver>





                  share|improve this answer































                    15 Answers
                    15






                    active

                    oldest

                    votes








                    15 Answers
                    15






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    222














                    Answer to your first question: Your broadcast receiver is being called two times because



                    You have added two <intent-filter>




                    1. Change in network connection :
                      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />


                    2. Change in WiFi state:
                      <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />



                    Just use one:
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />.



                    It will respond to only one action instead of two. See here for more information.



                    Answer to your second question (you want receiver to call only one time if internet connection available):



                    Your code is perfect; you notify only when internet is available.



                    UPDATE



                    You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.



                    public boolean isOnline(Context context) {

                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    //should check null because in airplane mode it will be null
                    return (netInfo != null && netInfo.isConnected());
                    }





                    share|improve this answer


























                    • No my second Query is I want notification when only the network is available but if the phone is loosing the network then to it is notifying me.

                      – Nikhil Agrawal
                      Mar 30 '13 at 5:58






                    • 7





                      same here. I just have <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> registered but my receiver still get called twice. It is not really big problem but I would like to know why.

                      – Yeung
                      May 8 '13 at 7:17






                    • 1





                      I am familiar with all of this , but I have doubts. I did some tests and found out that these broadcast receivers detect if your wifi / phone radio goes ON or OFF, or simply, if your device has an IP address. The problem comes when for example my phone is connected to a WiFi access point but such access point has no Internet. The code/phone tell me it a data connection regardless if the access point is providing it with Internet or Not. Does anybody know how to create a real Data-Internet listener, not just a WiFI/On/Off Listener?

                      – Josh
                      Jul 15 '14 at 10:07








                    • 4





                      @JosueGalindo onReceiving, you can use this code to know if device is connected to internet pastebin.com/dV3pJjkm

                      – Seshu Vinay
                      Jul 18 '14 at 6:47











                    • does this really check if the internet is available? or if it is just connected to a network where internet SHOULD be available.. if it is connected to a wifi network for instance that doesn't have an internet connection won't this still return true?

                      – erik
                      Apr 24 '15 at 12:57
















                    222














                    Answer to your first question: Your broadcast receiver is being called two times because



                    You have added two <intent-filter>




                    1. Change in network connection :
                      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />


                    2. Change in WiFi state:
                      <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />



                    Just use one:
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />.



                    It will respond to only one action instead of two. See here for more information.



                    Answer to your second question (you want receiver to call only one time if internet connection available):



                    Your code is perfect; you notify only when internet is available.



                    UPDATE



                    You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.



                    public boolean isOnline(Context context) {

                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    //should check null because in airplane mode it will be null
                    return (netInfo != null && netInfo.isConnected());
                    }





                    share|improve this answer


























                    • No my second Query is I want notification when only the network is available but if the phone is loosing the network then to it is notifying me.

                      – Nikhil Agrawal
                      Mar 30 '13 at 5:58






                    • 7





                      same here. I just have <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> registered but my receiver still get called twice. It is not really big problem but I would like to know why.

                      – Yeung
                      May 8 '13 at 7:17






                    • 1





                      I am familiar with all of this , but I have doubts. I did some tests and found out that these broadcast receivers detect if your wifi / phone radio goes ON or OFF, or simply, if your device has an IP address. The problem comes when for example my phone is connected to a WiFi access point but such access point has no Internet. The code/phone tell me it a data connection regardless if the access point is providing it with Internet or Not. Does anybody know how to create a real Data-Internet listener, not just a WiFI/On/Off Listener?

                      – Josh
                      Jul 15 '14 at 10:07








                    • 4





                      @JosueGalindo onReceiving, you can use this code to know if device is connected to internet pastebin.com/dV3pJjkm

                      – Seshu Vinay
                      Jul 18 '14 at 6:47











                    • does this really check if the internet is available? or if it is just connected to a network where internet SHOULD be available.. if it is connected to a wifi network for instance that doesn't have an internet connection won't this still return true?

                      – erik
                      Apr 24 '15 at 12:57














                    222












                    222








                    222







                    Answer to your first question: Your broadcast receiver is being called two times because



                    You have added two <intent-filter>




                    1. Change in network connection :
                      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />


                    2. Change in WiFi state:
                      <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />



                    Just use one:
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />.



                    It will respond to only one action instead of two. See here for more information.



                    Answer to your second question (you want receiver to call only one time if internet connection available):



                    Your code is perfect; you notify only when internet is available.



                    UPDATE



                    You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.



                    public boolean isOnline(Context context) {

                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    //should check null because in airplane mode it will be null
                    return (netInfo != null && netInfo.isConnected());
                    }





                    share|improve this answer















                    Answer to your first question: Your broadcast receiver is being called two times because



                    You have added two <intent-filter>




                    1. Change in network connection :
                      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />


                    2. Change in WiFi state:
                      <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />



                    Just use one:
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />.



                    It will respond to only one action instead of two. See here for more information.



                    Answer to your second question (you want receiver to call only one time if internet connection available):



                    Your code is perfect; you notify only when internet is available.



                    UPDATE



                    You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.



                    public boolean isOnline(Context context) {

                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    //should check null because in airplane mode it will be null
                    return (netInfo != null && netInfo.isConnected());
                    }






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 23 '17 at 12:02









                    Community

                    11




                    11










                    answered Mar 29 '13 at 9:39







                    user1381827




















                    • No my second Query is I want notification when only the network is available but if the phone is loosing the network then to it is notifying me.

                      – Nikhil Agrawal
                      Mar 30 '13 at 5:58






                    • 7





                      same here. I just have <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> registered but my receiver still get called twice. It is not really big problem but I would like to know why.

                      – Yeung
                      May 8 '13 at 7:17






                    • 1





                      I am familiar with all of this , but I have doubts. I did some tests and found out that these broadcast receivers detect if your wifi / phone radio goes ON or OFF, or simply, if your device has an IP address. The problem comes when for example my phone is connected to a WiFi access point but such access point has no Internet. The code/phone tell me it a data connection regardless if the access point is providing it with Internet or Not. Does anybody know how to create a real Data-Internet listener, not just a WiFI/On/Off Listener?

                      – Josh
                      Jul 15 '14 at 10:07








                    • 4





                      @JosueGalindo onReceiving, you can use this code to know if device is connected to internet pastebin.com/dV3pJjkm

                      – Seshu Vinay
                      Jul 18 '14 at 6:47











                    • does this really check if the internet is available? or if it is just connected to a network where internet SHOULD be available.. if it is connected to a wifi network for instance that doesn't have an internet connection won't this still return true?

                      – erik
                      Apr 24 '15 at 12:57



















                    • No my second Query is I want notification when only the network is available but if the phone is loosing the network then to it is notifying me.

                      – Nikhil Agrawal
                      Mar 30 '13 at 5:58






                    • 7





                      same here. I just have <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> registered but my receiver still get called twice. It is not really big problem but I would like to know why.

                      – Yeung
                      May 8 '13 at 7:17






                    • 1





                      I am familiar with all of this , but I have doubts. I did some tests and found out that these broadcast receivers detect if your wifi / phone radio goes ON or OFF, or simply, if your device has an IP address. The problem comes when for example my phone is connected to a WiFi access point but such access point has no Internet. The code/phone tell me it a data connection regardless if the access point is providing it with Internet or Not. Does anybody know how to create a real Data-Internet listener, not just a WiFI/On/Off Listener?

                      – Josh
                      Jul 15 '14 at 10:07








                    • 4





                      @JosueGalindo onReceiving, you can use this code to know if device is connected to internet pastebin.com/dV3pJjkm

                      – Seshu Vinay
                      Jul 18 '14 at 6:47











                    • does this really check if the internet is available? or if it is just connected to a network where internet SHOULD be available.. if it is connected to a wifi network for instance that doesn't have an internet connection won't this still return true?

                      – erik
                      Apr 24 '15 at 12:57

















                    No my second Query is I want notification when only the network is available but if the phone is loosing the network then to it is notifying me.

                    – Nikhil Agrawal
                    Mar 30 '13 at 5:58





                    No my second Query is I want notification when only the network is available but if the phone is loosing the network then to it is notifying me.

                    – Nikhil Agrawal
                    Mar 30 '13 at 5:58




                    7




                    7





                    same here. I just have <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> registered but my receiver still get called twice. It is not really big problem but I would like to know why.

                    – Yeung
                    May 8 '13 at 7:17





                    same here. I just have <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> registered but my receiver still get called twice. It is not really big problem but I would like to know why.

                    – Yeung
                    May 8 '13 at 7:17




                    1




                    1





                    I am familiar with all of this , but I have doubts. I did some tests and found out that these broadcast receivers detect if your wifi / phone radio goes ON or OFF, or simply, if your device has an IP address. The problem comes when for example my phone is connected to a WiFi access point but such access point has no Internet. The code/phone tell me it a data connection regardless if the access point is providing it with Internet or Not. Does anybody know how to create a real Data-Internet listener, not just a WiFI/On/Off Listener?

                    – Josh
                    Jul 15 '14 at 10:07







                    I am familiar with all of this , but I have doubts. I did some tests and found out that these broadcast receivers detect if your wifi / phone radio goes ON or OFF, or simply, if your device has an IP address. The problem comes when for example my phone is connected to a WiFi access point but such access point has no Internet. The code/phone tell me it a data connection regardless if the access point is providing it with Internet or Not. Does anybody know how to create a real Data-Internet listener, not just a WiFI/On/Off Listener?

                    – Josh
                    Jul 15 '14 at 10:07






                    4




                    4





                    @JosueGalindo onReceiving, you can use this code to know if device is connected to internet pastebin.com/dV3pJjkm

                    – Seshu Vinay
                    Jul 18 '14 at 6:47





                    @JosueGalindo onReceiving, you can use this code to know if device is connected to internet pastebin.com/dV3pJjkm

                    – Seshu Vinay
                    Jul 18 '14 at 6:47













                    does this really check if the internet is available? or if it is just connected to a network where internet SHOULD be available.. if it is connected to a wifi network for instance that doesn't have an internet connection won't this still return true?

                    – erik
                    Apr 24 '15 at 12:57





                    does this really check if the internet is available? or if it is just connected to a network where internet SHOULD be available.. if it is connected to a wifi network for instance that doesn't have an internet connection won't this still return true?

                    – erik
                    Apr 24 '15 at 12:57













                    70





                    +25









                    public class NetworkChangeReceiver extends BroadcastReceiver {

                    @Override
                    public void onReceive(final Context context, final Intent intent) {

                    if(checkInternet(context))
                    {
                    Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
                    }

                    }

                    boolean checkInternet(Context context) {
                    ServiceManager serviceManager = new ServiceManager(context);
                    if (serviceManager.isNetworkAvailable()) {
                    return true;
                    } else {
                    return false;
                    }
                    }

                    }


                    ServiceManager.java



                    public class ServiceManager {

                    Context context;

                    public ServiceManager(Context base) {
                    context = base;
                    }

                    public boolean isNetworkAvailable() {
                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
                    return networkInfo != null && networkInfo.isConnected();
                    }
                    }


                    permissions:



                     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
                    <uses-permission android:name="android.permission.INTERNET" />





                    share|improve this answer





















                    • 1





                      for me the problem was receiver gets called twice on network change?

                      – manivannan
                      Sep 30 '14 at 7:06






                    • 9





                      why would you use a ContextWrapper? Want to understand

                      – Darpan
                      Jun 25 '15 at 7:28






                    • 1





                      me also getting @manivannan problem... reciever calling twice on network change... is there any solution for that

                      – venkat
                      Jun 22 '16 at 5:17











                    • No need to extend ServiceManager with ContextWrapper.

                      – Yogesh Seralia
                      Jun 30 '16 at 11:16











                    • thx for reminding about ACCESS_NETWORK_STATE

                      – Defuera
                      Sep 1 '16 at 20:59
















                    70





                    +25









                    public class NetworkChangeReceiver extends BroadcastReceiver {

                    @Override
                    public void onReceive(final Context context, final Intent intent) {

                    if(checkInternet(context))
                    {
                    Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
                    }

                    }

                    boolean checkInternet(Context context) {
                    ServiceManager serviceManager = new ServiceManager(context);
                    if (serviceManager.isNetworkAvailable()) {
                    return true;
                    } else {
                    return false;
                    }
                    }

                    }


                    ServiceManager.java



                    public class ServiceManager {

                    Context context;

                    public ServiceManager(Context base) {
                    context = base;
                    }

                    public boolean isNetworkAvailable() {
                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
                    return networkInfo != null && networkInfo.isConnected();
                    }
                    }


                    permissions:



                     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
                    <uses-permission android:name="android.permission.INTERNET" />





                    share|improve this answer





















                    • 1





                      for me the problem was receiver gets called twice on network change?

                      – manivannan
                      Sep 30 '14 at 7:06






                    • 9





                      why would you use a ContextWrapper? Want to understand

                      – Darpan
                      Jun 25 '15 at 7:28






                    • 1





                      me also getting @manivannan problem... reciever calling twice on network change... is there any solution for that

                      – venkat
                      Jun 22 '16 at 5:17











                    • No need to extend ServiceManager with ContextWrapper.

                      – Yogesh Seralia
                      Jun 30 '16 at 11:16











                    • thx for reminding about ACCESS_NETWORK_STATE

                      – Defuera
                      Sep 1 '16 at 20:59














                    70





                    +25







                    70





                    +25



                    70




                    +25





                    public class NetworkChangeReceiver extends BroadcastReceiver {

                    @Override
                    public void onReceive(final Context context, final Intent intent) {

                    if(checkInternet(context))
                    {
                    Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
                    }

                    }

                    boolean checkInternet(Context context) {
                    ServiceManager serviceManager = new ServiceManager(context);
                    if (serviceManager.isNetworkAvailable()) {
                    return true;
                    } else {
                    return false;
                    }
                    }

                    }


                    ServiceManager.java



                    public class ServiceManager {

                    Context context;

                    public ServiceManager(Context base) {
                    context = base;
                    }

                    public boolean isNetworkAvailable() {
                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
                    return networkInfo != null && networkInfo.isConnected();
                    }
                    }


                    permissions:



                     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
                    <uses-permission android:name="android.permission.INTERNET" />





                    share|improve this answer















                    public class NetworkChangeReceiver extends BroadcastReceiver {

                    @Override
                    public void onReceive(final Context context, final Intent intent) {

                    if(checkInternet(context))
                    {
                    Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
                    }

                    }

                    boolean checkInternet(Context context) {
                    ServiceManager serviceManager = new ServiceManager(context);
                    if (serviceManager.isNetworkAvailable()) {
                    return true;
                    } else {
                    return false;
                    }
                    }

                    }


                    ServiceManager.java



                    public class ServiceManager {

                    Context context;

                    public ServiceManager(Context base) {
                    context = base;
                    }

                    public boolean isNetworkAvailable() {
                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
                    return networkInfo != null && networkInfo.isConnected();
                    }
                    }


                    permissions:



                     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
                    <uses-permission android:name="android.permission.INTERNET" />






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 13 '17 at 9:05









                    vrwim

                    3,90384285




                    3,90384285










                    answered Sep 30 '14 at 6:36









                    Vaishali SutariyaVaishali Sutariya

                    3,7782028




                    3,7782028








                    • 1





                      for me the problem was receiver gets called twice on network change?

                      – manivannan
                      Sep 30 '14 at 7:06






                    • 9





                      why would you use a ContextWrapper? Want to understand

                      – Darpan
                      Jun 25 '15 at 7:28






                    • 1





                      me also getting @manivannan problem... reciever calling twice on network change... is there any solution for that

                      – venkat
                      Jun 22 '16 at 5:17











                    • No need to extend ServiceManager with ContextWrapper.

                      – Yogesh Seralia
                      Jun 30 '16 at 11:16











                    • thx for reminding about ACCESS_NETWORK_STATE

                      – Defuera
                      Sep 1 '16 at 20:59














                    • 1





                      for me the problem was receiver gets called twice on network change?

                      – manivannan
                      Sep 30 '14 at 7:06






                    • 9





                      why would you use a ContextWrapper? Want to understand

                      – Darpan
                      Jun 25 '15 at 7:28






                    • 1





                      me also getting @manivannan problem... reciever calling twice on network change... is there any solution for that

                      – venkat
                      Jun 22 '16 at 5:17











                    • No need to extend ServiceManager with ContextWrapper.

                      – Yogesh Seralia
                      Jun 30 '16 at 11:16











                    • thx for reminding about ACCESS_NETWORK_STATE

                      – Defuera
                      Sep 1 '16 at 20:59








                    1




                    1





                    for me the problem was receiver gets called twice on network change?

                    – manivannan
                    Sep 30 '14 at 7:06





                    for me the problem was receiver gets called twice on network change?

                    – manivannan
                    Sep 30 '14 at 7:06




                    9




                    9





                    why would you use a ContextWrapper? Want to understand

                    – Darpan
                    Jun 25 '15 at 7:28





                    why would you use a ContextWrapper? Want to understand

                    – Darpan
                    Jun 25 '15 at 7:28




                    1




                    1





                    me also getting @manivannan problem... reciever calling twice on network change... is there any solution for that

                    – venkat
                    Jun 22 '16 at 5:17





                    me also getting @manivannan problem... reciever calling twice on network change... is there any solution for that

                    – venkat
                    Jun 22 '16 at 5:17













                    No need to extend ServiceManager with ContextWrapper.

                    – Yogesh Seralia
                    Jun 30 '16 at 11:16





                    No need to extend ServiceManager with ContextWrapper.

                    – Yogesh Seralia
                    Jun 30 '16 at 11:16













                    thx for reminding about ACCESS_NETWORK_STATE

                    – Defuera
                    Sep 1 '16 at 20:59





                    thx for reminding about ACCESS_NETWORK_STATE

                    – Defuera
                    Sep 1 '16 at 20:59











                    38














                    Checking internet status every time using Broadcast Receiver:



                    internet status implementation



                    Full source code available on Google Drive.



                    AndroidManifest.xml



                    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
                    <uses-permission android:name="android.permission.INTERNET"/>
                    <receiver android:name=".receivers.NetworkChangeReceiver">
                    <intent-filter>
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                    </intent-filter>
                    </receiver>


                    BroadcastReciever



                    package com.keshav.networkchangereceiverexample.receivers;

                    import android.content.BroadcastReceiver;
                    import android.content.Context;
                    import android.content.Intent;
                    import android.net.ConnectivityManager;
                    import android.net.NetworkInfo;
                    import android.util.Log;

                    import static com.keshav.networkchangereceiverexample.MainActivity.dialog;

                    public class NetworkChangeReceiver extends BroadcastReceiver
                    {
                    @Override
                    public void onReceive(Context context, Intent intent)
                    {
                    try
                    {
                    if (isOnline(context)) {
                    dialog(true);
                    Log.e("keshav", "Online Connect Intenet ");
                    } else {
                    dialog(false);
                    Log.e("keshav", "Conectivity Failure !!! ");
                    }
                    } catch (NullPointerException e) {
                    e.printStackTrace();
                    }
                    }

                    private boolean isOnline(Context context) {
                    try {
                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    //should check null because in airplane mode it will be null
                    return (netInfo != null && netInfo.isConnected());
                    } catch (NullPointerException e) {
                    e.printStackTrace();
                    return false;
                    }
                    }
                    }


                    MainActivity.java



                    package com.keshav.networkchangereceiverexample;

                    import android.content.BroadcastReceiver;
                    import android.content.Intent;
                    import android.content.IntentFilter;
                    import android.graphics.Color;
                    import android.net.ConnectivityManager;
                    import android.os.Build;
                    import android.os.Handler;
                    import android.os.Looper;
                    import android.support.v7.app.AppCompatActivity;
                    import android.os.Bundle;
                    import android.util.Log;
                    import android.view.View;
                    import android.view.animation.Animation;
                    import android.view.animation.AnimationUtils;
                    import android.widget.TextView;

                    import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver;

                    public class MainActivity extends AppCompatActivity {

                    private BroadcastReceiver mNetworkReceiver;
                    static TextView tv_check_connection;

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
                    mNetworkReceiver = new NetworkChangeReceiver();
                    registerNetworkBroadcastForNougat();

                    }

                    public static void dialog(boolean value){

                    if(value){
                    tv_check_connection.setText("We are back !!!");
                    tv_check_connection.setBackgroundColor(Color.GREEN);
                    tv_check_connection.setTextColor(Color.WHITE);

                    Handler handler = new Handler();
                    Runnable delayrunnable = new Runnable() {
                    @Override
                    public void run() {
                    tv_check_connection.setVisibility(View.GONE);
                    }
                    };
                    handler.postDelayed(delayrunnable, 3000);
                    }else {
                    tv_check_connection.setVisibility(View.VISIBLE);
                    tv_check_connection.setText("Could not Connect to internet");
                    tv_check_connection.setBackgroundColor(Color.RED);
                    tv_check_connection.setTextColor(Color.WHITE);
                    }
                    }


                    private void registerNetworkBroadcastForNougat() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    }
                    }

                    protected void unregisterNetworkChanges() {
                    try {
                    unregisterReceiver(mNetworkReceiver);
                    } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    }
                    }

                    @Override
                    public void onDestroy() {
                    super.onDestroy();
                    unregisterNetworkChanges();
                    }
                    }


                    activity_main.xml



                    <?xml version="1.0" encoding="utf-8"?>
                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    tools:context="com.keshav.networkchangereceiverexample.MainActivity">

                    <TextView
                    android:id="@+id/tv_check_connection"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Connection establised !"
                    android:padding="25dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    android:gravity="center"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                    </LinearLayout>





                    share|improve this answer


























                    • Its Very usefull same as youtube every time check online ,offline

                      – Keshav Gera
                      Aug 22 '17 at 7:33











                    • Thanks for your great post. Why did you add this: Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) in registerNetworkBroadcastForNougat? The manifest is not working in android N and Up and M shoud be fine

                      – Amir
                      Aug 26 '17 at 2:45











                    • Amir mind make up to Android N therefore i use

                      – Keshav Gera
                      Sep 12 '17 at 12:26








                    • 3





                      duplicate code at registerNetworkBroadcastForNougat()

                      – lenhuy2106
                      Jan 18 '18 at 21:38











                    • shouldnt there be a else in this code segment ? 'if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); }'

                      – Siddharth
                      May 30 '18 at 12:29
















                    38














                    Checking internet status every time using Broadcast Receiver:



                    internet status implementation



                    Full source code available on Google Drive.



                    AndroidManifest.xml



                    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
                    <uses-permission android:name="android.permission.INTERNET"/>
                    <receiver android:name=".receivers.NetworkChangeReceiver">
                    <intent-filter>
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                    </intent-filter>
                    </receiver>


                    BroadcastReciever



                    package com.keshav.networkchangereceiverexample.receivers;

                    import android.content.BroadcastReceiver;
                    import android.content.Context;
                    import android.content.Intent;
                    import android.net.ConnectivityManager;
                    import android.net.NetworkInfo;
                    import android.util.Log;

                    import static com.keshav.networkchangereceiverexample.MainActivity.dialog;

                    public class NetworkChangeReceiver extends BroadcastReceiver
                    {
                    @Override
                    public void onReceive(Context context, Intent intent)
                    {
                    try
                    {
                    if (isOnline(context)) {
                    dialog(true);
                    Log.e("keshav", "Online Connect Intenet ");
                    } else {
                    dialog(false);
                    Log.e("keshav", "Conectivity Failure !!! ");
                    }
                    } catch (NullPointerException e) {
                    e.printStackTrace();
                    }
                    }

                    private boolean isOnline(Context context) {
                    try {
                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    //should check null because in airplane mode it will be null
                    return (netInfo != null && netInfo.isConnected());
                    } catch (NullPointerException e) {
                    e.printStackTrace();
                    return false;
                    }
                    }
                    }


                    MainActivity.java



                    package com.keshav.networkchangereceiverexample;

                    import android.content.BroadcastReceiver;
                    import android.content.Intent;
                    import android.content.IntentFilter;
                    import android.graphics.Color;
                    import android.net.ConnectivityManager;
                    import android.os.Build;
                    import android.os.Handler;
                    import android.os.Looper;
                    import android.support.v7.app.AppCompatActivity;
                    import android.os.Bundle;
                    import android.util.Log;
                    import android.view.View;
                    import android.view.animation.Animation;
                    import android.view.animation.AnimationUtils;
                    import android.widget.TextView;

                    import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver;

                    public class MainActivity extends AppCompatActivity {

                    private BroadcastReceiver mNetworkReceiver;
                    static TextView tv_check_connection;

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
                    mNetworkReceiver = new NetworkChangeReceiver();
                    registerNetworkBroadcastForNougat();

                    }

                    public static void dialog(boolean value){

                    if(value){
                    tv_check_connection.setText("We are back !!!");
                    tv_check_connection.setBackgroundColor(Color.GREEN);
                    tv_check_connection.setTextColor(Color.WHITE);

                    Handler handler = new Handler();
                    Runnable delayrunnable = new Runnable() {
                    @Override
                    public void run() {
                    tv_check_connection.setVisibility(View.GONE);
                    }
                    };
                    handler.postDelayed(delayrunnable, 3000);
                    }else {
                    tv_check_connection.setVisibility(View.VISIBLE);
                    tv_check_connection.setText("Could not Connect to internet");
                    tv_check_connection.setBackgroundColor(Color.RED);
                    tv_check_connection.setTextColor(Color.WHITE);
                    }
                    }


                    private void registerNetworkBroadcastForNougat() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    }
                    }

                    protected void unregisterNetworkChanges() {
                    try {
                    unregisterReceiver(mNetworkReceiver);
                    } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    }
                    }

                    @Override
                    public void onDestroy() {
                    super.onDestroy();
                    unregisterNetworkChanges();
                    }
                    }


                    activity_main.xml



                    <?xml version="1.0" encoding="utf-8"?>
                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    tools:context="com.keshav.networkchangereceiverexample.MainActivity">

                    <TextView
                    android:id="@+id/tv_check_connection"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Connection establised !"
                    android:padding="25dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    android:gravity="center"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                    </LinearLayout>





                    share|improve this answer


























                    • Its Very usefull same as youtube every time check online ,offline

                      – Keshav Gera
                      Aug 22 '17 at 7:33











                    • Thanks for your great post. Why did you add this: Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) in registerNetworkBroadcastForNougat? The manifest is not working in android N and Up and M shoud be fine

                      – Amir
                      Aug 26 '17 at 2:45











                    • Amir mind make up to Android N therefore i use

                      – Keshav Gera
                      Sep 12 '17 at 12:26








                    • 3





                      duplicate code at registerNetworkBroadcastForNougat()

                      – lenhuy2106
                      Jan 18 '18 at 21:38











                    • shouldnt there be a else in this code segment ? 'if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); }'

                      – Siddharth
                      May 30 '18 at 12:29














                    38












                    38








                    38







                    Checking internet status every time using Broadcast Receiver:



                    internet status implementation



                    Full source code available on Google Drive.



                    AndroidManifest.xml



                    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
                    <uses-permission android:name="android.permission.INTERNET"/>
                    <receiver android:name=".receivers.NetworkChangeReceiver">
                    <intent-filter>
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                    </intent-filter>
                    </receiver>


                    BroadcastReciever



                    package com.keshav.networkchangereceiverexample.receivers;

                    import android.content.BroadcastReceiver;
                    import android.content.Context;
                    import android.content.Intent;
                    import android.net.ConnectivityManager;
                    import android.net.NetworkInfo;
                    import android.util.Log;

                    import static com.keshav.networkchangereceiverexample.MainActivity.dialog;

                    public class NetworkChangeReceiver extends BroadcastReceiver
                    {
                    @Override
                    public void onReceive(Context context, Intent intent)
                    {
                    try
                    {
                    if (isOnline(context)) {
                    dialog(true);
                    Log.e("keshav", "Online Connect Intenet ");
                    } else {
                    dialog(false);
                    Log.e("keshav", "Conectivity Failure !!! ");
                    }
                    } catch (NullPointerException e) {
                    e.printStackTrace();
                    }
                    }

                    private boolean isOnline(Context context) {
                    try {
                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    //should check null because in airplane mode it will be null
                    return (netInfo != null && netInfo.isConnected());
                    } catch (NullPointerException e) {
                    e.printStackTrace();
                    return false;
                    }
                    }
                    }


                    MainActivity.java



                    package com.keshav.networkchangereceiverexample;

                    import android.content.BroadcastReceiver;
                    import android.content.Intent;
                    import android.content.IntentFilter;
                    import android.graphics.Color;
                    import android.net.ConnectivityManager;
                    import android.os.Build;
                    import android.os.Handler;
                    import android.os.Looper;
                    import android.support.v7.app.AppCompatActivity;
                    import android.os.Bundle;
                    import android.util.Log;
                    import android.view.View;
                    import android.view.animation.Animation;
                    import android.view.animation.AnimationUtils;
                    import android.widget.TextView;

                    import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver;

                    public class MainActivity extends AppCompatActivity {

                    private BroadcastReceiver mNetworkReceiver;
                    static TextView tv_check_connection;

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
                    mNetworkReceiver = new NetworkChangeReceiver();
                    registerNetworkBroadcastForNougat();

                    }

                    public static void dialog(boolean value){

                    if(value){
                    tv_check_connection.setText("We are back !!!");
                    tv_check_connection.setBackgroundColor(Color.GREEN);
                    tv_check_connection.setTextColor(Color.WHITE);

                    Handler handler = new Handler();
                    Runnable delayrunnable = new Runnable() {
                    @Override
                    public void run() {
                    tv_check_connection.setVisibility(View.GONE);
                    }
                    };
                    handler.postDelayed(delayrunnable, 3000);
                    }else {
                    tv_check_connection.setVisibility(View.VISIBLE);
                    tv_check_connection.setText("Could not Connect to internet");
                    tv_check_connection.setBackgroundColor(Color.RED);
                    tv_check_connection.setTextColor(Color.WHITE);
                    }
                    }


                    private void registerNetworkBroadcastForNougat() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    }
                    }

                    protected void unregisterNetworkChanges() {
                    try {
                    unregisterReceiver(mNetworkReceiver);
                    } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    }
                    }

                    @Override
                    public void onDestroy() {
                    super.onDestroy();
                    unregisterNetworkChanges();
                    }
                    }


                    activity_main.xml



                    <?xml version="1.0" encoding="utf-8"?>
                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    tools:context="com.keshav.networkchangereceiverexample.MainActivity">

                    <TextView
                    android:id="@+id/tv_check_connection"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Connection establised !"
                    android:padding="25dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    android:gravity="center"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                    </LinearLayout>





                    share|improve this answer















                    Checking internet status every time using Broadcast Receiver:



                    internet status implementation



                    Full source code available on Google Drive.



                    AndroidManifest.xml



                    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
                    <uses-permission android:name="android.permission.INTERNET"/>
                    <receiver android:name=".receivers.NetworkChangeReceiver">
                    <intent-filter>
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                    </intent-filter>
                    </receiver>


                    BroadcastReciever



                    package com.keshav.networkchangereceiverexample.receivers;

                    import android.content.BroadcastReceiver;
                    import android.content.Context;
                    import android.content.Intent;
                    import android.net.ConnectivityManager;
                    import android.net.NetworkInfo;
                    import android.util.Log;

                    import static com.keshav.networkchangereceiverexample.MainActivity.dialog;

                    public class NetworkChangeReceiver extends BroadcastReceiver
                    {
                    @Override
                    public void onReceive(Context context, Intent intent)
                    {
                    try
                    {
                    if (isOnline(context)) {
                    dialog(true);
                    Log.e("keshav", "Online Connect Intenet ");
                    } else {
                    dialog(false);
                    Log.e("keshav", "Conectivity Failure !!! ");
                    }
                    } catch (NullPointerException e) {
                    e.printStackTrace();
                    }
                    }

                    private boolean isOnline(Context context) {
                    try {
                    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getActiveNetworkInfo();
                    //should check null because in airplane mode it will be null
                    return (netInfo != null && netInfo.isConnected());
                    } catch (NullPointerException e) {
                    e.printStackTrace();
                    return false;
                    }
                    }
                    }


                    MainActivity.java



                    package com.keshav.networkchangereceiverexample;

                    import android.content.BroadcastReceiver;
                    import android.content.Intent;
                    import android.content.IntentFilter;
                    import android.graphics.Color;
                    import android.net.ConnectivityManager;
                    import android.os.Build;
                    import android.os.Handler;
                    import android.os.Looper;
                    import android.support.v7.app.AppCompatActivity;
                    import android.os.Bundle;
                    import android.util.Log;
                    import android.view.View;
                    import android.view.animation.Animation;
                    import android.view.animation.AnimationUtils;
                    import android.widget.TextView;

                    import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver;

                    public class MainActivity extends AppCompatActivity {

                    private BroadcastReceiver mNetworkReceiver;
                    static TextView tv_check_connection;

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
                    mNetworkReceiver = new NetworkChangeReceiver();
                    registerNetworkBroadcastForNougat();

                    }

                    public static void dialog(boolean value){

                    if(value){
                    tv_check_connection.setText("We are back !!!");
                    tv_check_connection.setBackgroundColor(Color.GREEN);
                    tv_check_connection.setTextColor(Color.WHITE);

                    Handler handler = new Handler();
                    Runnable delayrunnable = new Runnable() {
                    @Override
                    public void run() {
                    tv_check_connection.setVisibility(View.GONE);
                    }
                    };
                    handler.postDelayed(delayrunnable, 3000);
                    }else {
                    tv_check_connection.setVisibility(View.VISIBLE);
                    tv_check_connection.setText("Could not Connect to internet");
                    tv_check_connection.setBackgroundColor(Color.RED);
                    tv_check_connection.setTextColor(Color.WHITE);
                    }
                    }


                    private void registerNetworkBroadcastForNougat() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    }
                    }

                    protected void unregisterNetworkChanges() {
                    try {
                    unregisterReceiver(mNetworkReceiver);
                    } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    }
                    }

                    @Override
                    public void onDestroy() {
                    super.onDestroy();
                    unregisterNetworkChanges();
                    }
                    }


                    activity_main.xml



                    <?xml version="1.0" encoding="utf-8"?>
                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    tools:context="com.keshav.networkchangereceiverexample.MainActivity">

                    <TextView
                    android:id="@+id/tv_check_connection"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Connection establised !"
                    android:padding="25dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    android:gravity="center"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                    </LinearLayout>






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 21 at 16:44









                    JakeSteam

                    1,97842336




                    1,97842336










                    answered Jul 3 '17 at 9:02









                    Keshav GeraKeshav Gera

                    2,6411728




                    2,6411728













                    • Its Very usefull same as youtube every time check online ,offline

                      – Keshav Gera
                      Aug 22 '17 at 7:33











                    • Thanks for your great post. Why did you add this: Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) in registerNetworkBroadcastForNougat? The manifest is not working in android N and Up and M shoud be fine

                      – Amir
                      Aug 26 '17 at 2:45











                    • Amir mind make up to Android N therefore i use

                      – Keshav Gera
                      Sep 12 '17 at 12:26








                    • 3





                      duplicate code at registerNetworkBroadcastForNougat()

                      – lenhuy2106
                      Jan 18 '18 at 21:38











                    • shouldnt there be a else in this code segment ? 'if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); }'

                      – Siddharth
                      May 30 '18 at 12:29



















                    • Its Very usefull same as youtube every time check online ,offline

                      – Keshav Gera
                      Aug 22 '17 at 7:33











                    • Thanks for your great post. Why did you add this: Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) in registerNetworkBroadcastForNougat? The manifest is not working in android N and Up and M shoud be fine

                      – Amir
                      Aug 26 '17 at 2:45











                    • Amir mind make up to Android N therefore i use

                      – Keshav Gera
                      Sep 12 '17 at 12:26








                    • 3





                      duplicate code at registerNetworkBroadcastForNougat()

                      – lenhuy2106
                      Jan 18 '18 at 21:38











                    • shouldnt there be a else in this code segment ? 'if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); }'

                      – Siddharth
                      May 30 '18 at 12:29

















                    Its Very usefull same as youtube every time check online ,offline

                    – Keshav Gera
                    Aug 22 '17 at 7:33





                    Its Very usefull same as youtube every time check online ,offline

                    – Keshav Gera
                    Aug 22 '17 at 7:33













                    Thanks for your great post. Why did you add this: Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) in registerNetworkBroadcastForNougat? The manifest is not working in android N and Up and M shoud be fine

                    – Amir
                    Aug 26 '17 at 2:45





                    Thanks for your great post. Why did you add this: Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) in registerNetworkBroadcastForNougat? The manifest is not working in android N and Up and M shoud be fine

                    – Amir
                    Aug 26 '17 at 2:45













                    Amir mind make up to Android N therefore i use

                    – Keshav Gera
                    Sep 12 '17 at 12:26







                    Amir mind make up to Android N therefore i use

                    – Keshav Gera
                    Sep 12 '17 at 12:26






                    3




                    3





                    duplicate code at registerNetworkBroadcastForNougat()

                    – lenhuy2106
                    Jan 18 '18 at 21:38





                    duplicate code at registerNetworkBroadcastForNougat()

                    – lenhuy2106
                    Jan 18 '18 at 21:38













                    shouldnt there be a else in this code segment ? 'if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); }'

                    – Siddharth
                    May 30 '18 at 12:29





                    shouldnt there be a else in this code segment ? 'if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); }'

                    – Siddharth
                    May 30 '18 at 12:29











                    25














                    Use this method to check the network state:



                    private void checkInternetConnection() {

                    if (br == null) {

                    br = new BroadcastReceiver() {

                    @Override
                    public void onReceive(Context context, Intent intent) {

                    Bundle extras = intent.getExtras();

                    NetworkInfo info = (NetworkInfo) extras
                    .getParcelable("networkInfo");

                    State state = info.getState();
                    Log.d("TEST Internet", info.toString() + " "
                    + state.toString());

                    if (state == State.CONNECTED) {
                    Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();

                    } else {
                    Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
                    }

                    }
                    };

                    final IntentFilter intentFilter = new IntentFilter();
                    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                    registerReceiver((BroadcastReceiver) br, intentFilter);
                    }
                    }


                    remember to unregister service in onDestroy.



                    Cheers!!






                    share|improve this answer




























                      25














                      Use this method to check the network state:



                      private void checkInternetConnection() {

                      if (br == null) {

                      br = new BroadcastReceiver() {

                      @Override
                      public void onReceive(Context context, Intent intent) {

                      Bundle extras = intent.getExtras();

                      NetworkInfo info = (NetworkInfo) extras
                      .getParcelable("networkInfo");

                      State state = info.getState();
                      Log.d("TEST Internet", info.toString() + " "
                      + state.toString());

                      if (state == State.CONNECTED) {
                      Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();

                      } else {
                      Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
                      }

                      }
                      };

                      final IntentFilter intentFilter = new IntentFilter();
                      intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                      registerReceiver((BroadcastReceiver) br, intentFilter);
                      }
                      }


                      remember to unregister service in onDestroy.



                      Cheers!!






                      share|improve this answer


























                        25












                        25








                        25







                        Use this method to check the network state:



                        private void checkInternetConnection() {

                        if (br == null) {

                        br = new BroadcastReceiver() {

                        @Override
                        public void onReceive(Context context, Intent intent) {

                        Bundle extras = intent.getExtras();

                        NetworkInfo info = (NetworkInfo) extras
                        .getParcelable("networkInfo");

                        State state = info.getState();
                        Log.d("TEST Internet", info.toString() + " "
                        + state.toString());

                        if (state == State.CONNECTED) {
                        Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();

                        } else {
                        Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
                        }

                        }
                        };

                        final IntentFilter intentFilter = new IntentFilter();
                        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                        registerReceiver((BroadcastReceiver) br, intentFilter);
                        }
                        }


                        remember to unregister service in onDestroy.



                        Cheers!!






                        share|improve this answer













                        Use this method to check the network state:



                        private void checkInternetConnection() {

                        if (br == null) {

                        br = new BroadcastReceiver() {

                        @Override
                        public void onReceive(Context context, Intent intent) {

                        Bundle extras = intent.getExtras();

                        NetworkInfo info = (NetworkInfo) extras
                        .getParcelable("networkInfo");

                        State state = info.getState();
                        Log.d("TEST Internet", info.toString() + " "
                        + state.toString());

                        if (state == State.CONNECTED) {
                        Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();

                        } else {
                        Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
                        }

                        }
                        };

                        final IntentFilter intentFilter = new IntentFilter();
                        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                        registerReceiver((BroadcastReceiver) br, intentFilter);
                        }
                        }


                        remember to unregister service in onDestroy.



                        Cheers!!







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Sep 4 '15 at 5:32









                        Aj 27Aj 27

                        1,646924




                        1,646924























                            9














                            public static boolean isNetworkAvailable(Context context) {
                            boolean isMobile = false, isWifi = false;

                            NetworkInfo infoAvailableNetworks = getConnectivityManagerInstance(
                            context).getAllNetworkInfo();

                            if (infoAvailableNetworks != null) {
                            for (NetworkInfo network : infoAvailableNetworks) {

                            if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                            if (network.isConnected() && network.isAvailable())
                            isWifi = true;
                            }
                            if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                            if (network.isConnected() && network.isAvailable())
                            isMobile = true;
                            }
                            }
                            }

                            return isMobile || isWifi;
                            }

                            /* You can write such method somewhere in utility class and call it NetworkChangeReceiver like below */
                            public class NetworkChangedReceiver extends BroadcastReceiver
                            {
                            @Override
                            public void onReceive(Context context, Intent intent) {

                            if (isNetworkAvailable(context))
                            {
                            Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();


                            }
                            }
                            }


                            This above broadcast receiver will be called only when Network state change to connected and not on disconnected.






                            share|improve this answer






























                              9














                              public static boolean isNetworkAvailable(Context context) {
                              boolean isMobile = false, isWifi = false;

                              NetworkInfo infoAvailableNetworks = getConnectivityManagerInstance(
                              context).getAllNetworkInfo();

                              if (infoAvailableNetworks != null) {
                              for (NetworkInfo network : infoAvailableNetworks) {

                              if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                              if (network.isConnected() && network.isAvailable())
                              isWifi = true;
                              }
                              if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                              if (network.isConnected() && network.isAvailable())
                              isMobile = true;
                              }
                              }
                              }

                              return isMobile || isWifi;
                              }

                              /* You can write such method somewhere in utility class and call it NetworkChangeReceiver like below */
                              public class NetworkChangedReceiver extends BroadcastReceiver
                              {
                              @Override
                              public void onReceive(Context context, Intent intent) {

                              if (isNetworkAvailable(context))
                              {
                              Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();


                              }
                              }
                              }


                              This above broadcast receiver will be called only when Network state change to connected and not on disconnected.






                              share|improve this answer




























                                9












                                9








                                9







                                public static boolean isNetworkAvailable(Context context) {
                                boolean isMobile = false, isWifi = false;

                                NetworkInfo infoAvailableNetworks = getConnectivityManagerInstance(
                                context).getAllNetworkInfo();

                                if (infoAvailableNetworks != null) {
                                for (NetworkInfo network : infoAvailableNetworks) {

                                if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                                if (network.isConnected() && network.isAvailable())
                                isWifi = true;
                                }
                                if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                                if (network.isConnected() && network.isAvailable())
                                isMobile = true;
                                }
                                }
                                }

                                return isMobile || isWifi;
                                }

                                /* You can write such method somewhere in utility class and call it NetworkChangeReceiver like below */
                                public class NetworkChangedReceiver extends BroadcastReceiver
                                {
                                @Override
                                public void onReceive(Context context, Intent intent) {

                                if (isNetworkAvailable(context))
                                {
                                Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();


                                }
                                }
                                }


                                This above broadcast receiver will be called only when Network state change to connected and not on disconnected.






                                share|improve this answer















                                public static boolean isNetworkAvailable(Context context) {
                                boolean isMobile = false, isWifi = false;

                                NetworkInfo infoAvailableNetworks = getConnectivityManagerInstance(
                                context).getAllNetworkInfo();

                                if (infoAvailableNetworks != null) {
                                for (NetworkInfo network : infoAvailableNetworks) {

                                if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                                if (network.isConnected() && network.isAvailable())
                                isWifi = true;
                                }
                                if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                                if (network.isConnected() && network.isAvailable())
                                isMobile = true;
                                }
                                }
                                }

                                return isMobile || isWifi;
                                }

                                /* You can write such method somewhere in utility class and call it NetworkChangeReceiver like below */
                                public class NetworkChangedReceiver extends BroadcastReceiver
                                {
                                @Override
                                public void onReceive(Context context, Intent intent) {

                                if (isNetworkAvailable(context))
                                {
                                Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();


                                }
                                }
                                }


                                This above broadcast receiver will be called only when Network state change to connected and not on disconnected.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Oct 16 '15 at 15:58









                                reika

                                1247




                                1247










                                answered Nov 27 '13 at 7:29









                                AniAni

                                11426




                                11426























                                    7














                                    Try with this



                                    public class ConnectionBroadcastReceiver extends BroadcastReceiver {
                                    @Override
                                    public void onReceive(Context context, Intent intent) {


                                    if (<Check internet connection available >) {
                                    Toast.makeText(context, "connect to the internet", Toast.LENGTH_LONG).show();

                                    /*upload background upload service*/
                                    Intent serviceIntent = new Intent(context,<your service class>);
                                    context.startService(serviceIntent);


                                    }else{
                                    Toast.makeText(context, "Connection faild", Toast.LENGTH_LONG).show();

                                    }




                                    }
                                    }


                                    This is the broadcast Receiver. soon as internet connection trigger this will loaded






                                    share|improve this answer


























                                    • And how do you register this receiver? What intent filter?

                                      – Stealth Rabbi
                                      Jan 27 '16 at 19:11
















                                    7














                                    Try with this



                                    public class ConnectionBroadcastReceiver extends BroadcastReceiver {
                                    @Override
                                    public void onReceive(Context context, Intent intent) {


                                    if (<Check internet connection available >) {
                                    Toast.makeText(context, "connect to the internet", Toast.LENGTH_LONG).show();

                                    /*upload background upload service*/
                                    Intent serviceIntent = new Intent(context,<your service class>);
                                    context.startService(serviceIntent);


                                    }else{
                                    Toast.makeText(context, "Connection faild", Toast.LENGTH_LONG).show();

                                    }




                                    }
                                    }


                                    This is the broadcast Receiver. soon as internet connection trigger this will loaded






                                    share|improve this answer


























                                    • And how do you register this receiver? What intent filter?

                                      – Stealth Rabbi
                                      Jan 27 '16 at 19:11














                                    7












                                    7








                                    7







                                    Try with this



                                    public class ConnectionBroadcastReceiver extends BroadcastReceiver {
                                    @Override
                                    public void onReceive(Context context, Intent intent) {


                                    if (<Check internet connection available >) {
                                    Toast.makeText(context, "connect to the internet", Toast.LENGTH_LONG).show();

                                    /*upload background upload service*/
                                    Intent serviceIntent = new Intent(context,<your service class>);
                                    context.startService(serviceIntent);


                                    }else{
                                    Toast.makeText(context, "Connection faild", Toast.LENGTH_LONG).show();

                                    }




                                    }
                                    }


                                    This is the broadcast Receiver. soon as internet connection trigger this will loaded






                                    share|improve this answer















                                    Try with this



                                    public class ConnectionBroadcastReceiver extends BroadcastReceiver {
                                    @Override
                                    public void onReceive(Context context, Intent intent) {


                                    if (<Check internet connection available >) {
                                    Toast.makeText(context, "connect to the internet", Toast.LENGTH_LONG).show();

                                    /*upload background upload service*/
                                    Intent serviceIntent = new Intent(context,<your service class>);
                                    context.startService(serviceIntent);


                                    }else{
                                    Toast.makeText(context, "Connection faild", Toast.LENGTH_LONG).show();

                                    }




                                    }
                                    }


                                    This is the broadcast Receiver. soon as internet connection trigger this will loaded







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Oct 13 '14 at 15:32









                                    TNR

                                    5,45632659




                                    5,45632659










                                    answered Sep 25 '14 at 10:46









                                    ayesh donayesh don

                                    590813




                                    590813













                                    • And how do you register this receiver? What intent filter?

                                      – Stealth Rabbi
                                      Jan 27 '16 at 19:11



















                                    • And how do you register this receiver? What intent filter?

                                      – Stealth Rabbi
                                      Jan 27 '16 at 19:11

















                                    And how do you register this receiver? What intent filter?

                                    – Stealth Rabbi
                                    Jan 27 '16 at 19:11





                                    And how do you register this receiver? What intent filter?

                                    – Stealth Rabbi
                                    Jan 27 '16 at 19:11











                                    7














                                    I know this thread is old and fully answered but I feel that the following might help some people.



                                    The code in the body of the question contains a bug which no one here addressed.
                                    @Nikhil is checking whether the wifi/mobile is available and not if it's connected.



                                    The fix is here:



                                    @Override
                                    public void onReceive(final Context context, final Intent intent) {
                                    final ConnectivityManager connMgr = (ConnectivityManager) context
                                    .getSystemService(Context.CONNECTIVITY_SERVICE);

                                    final android.net.NetworkInfo wifi = connMgr
                                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                                    final android.net.NetworkInfo mobile = connMgr
                                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                                    if (wifi.isConnected() || mobile.isConnected()) {
                                    // do stuff
                                    }
                                    }





                                    share|improve this answer


























                                    • Yes, I just want to suggest the same, wifi.isConnected() fix

                                      – Erich García
                                      Sep 17 '17 at 3:27
















                                    7














                                    I know this thread is old and fully answered but I feel that the following might help some people.



                                    The code in the body of the question contains a bug which no one here addressed.
                                    @Nikhil is checking whether the wifi/mobile is available and not if it's connected.



                                    The fix is here:



                                    @Override
                                    public void onReceive(final Context context, final Intent intent) {
                                    final ConnectivityManager connMgr = (ConnectivityManager) context
                                    .getSystemService(Context.CONNECTIVITY_SERVICE);

                                    final android.net.NetworkInfo wifi = connMgr
                                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                                    final android.net.NetworkInfo mobile = connMgr
                                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                                    if (wifi.isConnected() || mobile.isConnected()) {
                                    // do stuff
                                    }
                                    }





                                    share|improve this answer


























                                    • Yes, I just want to suggest the same, wifi.isConnected() fix

                                      – Erich García
                                      Sep 17 '17 at 3:27














                                    7












                                    7








                                    7







                                    I know this thread is old and fully answered but I feel that the following might help some people.



                                    The code in the body of the question contains a bug which no one here addressed.
                                    @Nikhil is checking whether the wifi/mobile is available and not if it's connected.



                                    The fix is here:



                                    @Override
                                    public void onReceive(final Context context, final Intent intent) {
                                    final ConnectivityManager connMgr = (ConnectivityManager) context
                                    .getSystemService(Context.CONNECTIVITY_SERVICE);

                                    final android.net.NetworkInfo wifi = connMgr
                                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                                    final android.net.NetworkInfo mobile = connMgr
                                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                                    if (wifi.isConnected() || mobile.isConnected()) {
                                    // do stuff
                                    }
                                    }





                                    share|improve this answer















                                    I know this thread is old and fully answered but I feel that the following might help some people.



                                    The code in the body of the question contains a bug which no one here addressed.
                                    @Nikhil is checking whether the wifi/mobile is available and not if it's connected.



                                    The fix is here:



                                    @Override
                                    public void onReceive(final Context context, final Intent intent) {
                                    final ConnectivityManager connMgr = (ConnectivityManager) context
                                    .getSystemService(Context.CONNECTIVITY_SERVICE);

                                    final android.net.NetworkInfo wifi = connMgr
                                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                                    final android.net.NetworkInfo mobile = connMgr
                                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                                    if (wifi.isConnected() || mobile.isConnected()) {
                                    // do stuff
                                    }
                                    }






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Jun 20 '16 at 15:53

























                                    answered Jun 6 '16 at 9:34









                                    NativNativ

                                    1,79842954




                                    1,79842954













                                    • Yes, I just want to suggest the same, wifi.isConnected() fix

                                      – Erich García
                                      Sep 17 '17 at 3:27



















                                    • Yes, I just want to suggest the same, wifi.isConnected() fix

                                      – Erich García
                                      Sep 17 '17 at 3:27

















                                    Yes, I just want to suggest the same, wifi.isConnected() fix

                                    – Erich García
                                    Sep 17 '17 at 3:27





                                    Yes, I just want to suggest the same, wifi.isConnected() fix

                                    – Erich García
                                    Sep 17 '17 at 3:27











                                    6














                                    manifest:



                                    <receiver android:name=".your.namepackage.here.ConnectivityReceiver">
                                    <intent-filter>
                                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                                    </intent-filter>
                                    </receiver>


                                    class for receiver:



                                    public class ConnectivityReceiver extends BroadcastReceiver{

                                    @Override
                                    public void onReceive(Context context, Intent intent) {
                                    final String action = intent.getAction();
                                    switch (action) {
                                    case ConnectivityManager.CONNECTIVITY_ACTION:
                                    DebugUtils.logDebug("BROADCAST", "network change");
                                    if(NetworkUtils.isConnect()){
                                    //do action here
                                    }
                                    break;
                                    }
                                    }
                                    }


                                    and classs utils like example:



                                    public class NetworkUtils {

                                    public static boolean isConnect() {
                                    ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                    Network netArray = connectivityManager.getAllNetworks();
                                    NetworkInfo netInfo;
                                    for (Network net : netArray) {
                                    netInfo = connectivityManager.getNetworkInfo(net);
                                    if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                                    //if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                                    Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                                    return true;
                                    }
                                    }
                                    } else {
                                    if (connectivityManager != null) {
                                    @SuppressWarnings("deprecation")
                                    NetworkInfo netInfoArray = connectivityManager.getAllNetworkInfo();
                                    if (netInfoArray != null) {
                                    for (NetworkInfo netInfo : netInfoArray) {
                                    if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                                    //if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
                                    Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                                    return true;
                                    }
                                    }
                                    }
                                    }
                                    }
                                    return false;
                                    }
                                    }





                                    share|improve this answer






























                                      6














                                      manifest:



                                      <receiver android:name=".your.namepackage.here.ConnectivityReceiver">
                                      <intent-filter>
                                      <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                                      </intent-filter>
                                      </receiver>


                                      class for receiver:



                                      public class ConnectivityReceiver extends BroadcastReceiver{

                                      @Override
                                      public void onReceive(Context context, Intent intent) {
                                      final String action = intent.getAction();
                                      switch (action) {
                                      case ConnectivityManager.CONNECTIVITY_ACTION:
                                      DebugUtils.logDebug("BROADCAST", "network change");
                                      if(NetworkUtils.isConnect()){
                                      //do action here
                                      }
                                      break;
                                      }
                                      }
                                      }


                                      and classs utils like example:



                                      public class NetworkUtils {

                                      public static boolean isConnect() {
                                      ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
                                      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                      Network netArray = connectivityManager.getAllNetworks();
                                      NetworkInfo netInfo;
                                      for (Network net : netArray) {
                                      netInfo = connectivityManager.getNetworkInfo(net);
                                      if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                                      //if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                                      Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                                      return true;
                                      }
                                      }
                                      } else {
                                      if (connectivityManager != null) {
                                      @SuppressWarnings("deprecation")
                                      NetworkInfo netInfoArray = connectivityManager.getAllNetworkInfo();
                                      if (netInfoArray != null) {
                                      for (NetworkInfo netInfo : netInfoArray) {
                                      if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                                      //if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
                                      Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                                      return true;
                                      }
                                      }
                                      }
                                      }
                                      }
                                      return false;
                                      }
                                      }





                                      share|improve this answer




























                                        6












                                        6








                                        6







                                        manifest:



                                        <receiver android:name=".your.namepackage.here.ConnectivityReceiver">
                                        <intent-filter>
                                        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                                        </intent-filter>
                                        </receiver>


                                        class for receiver:



                                        public class ConnectivityReceiver extends BroadcastReceiver{

                                        @Override
                                        public void onReceive(Context context, Intent intent) {
                                        final String action = intent.getAction();
                                        switch (action) {
                                        case ConnectivityManager.CONNECTIVITY_ACTION:
                                        DebugUtils.logDebug("BROADCAST", "network change");
                                        if(NetworkUtils.isConnect()){
                                        //do action here
                                        }
                                        break;
                                        }
                                        }
                                        }


                                        and classs utils like example:



                                        public class NetworkUtils {

                                        public static boolean isConnect() {
                                        ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        Network netArray = connectivityManager.getAllNetworks();
                                        NetworkInfo netInfo;
                                        for (Network net : netArray) {
                                        netInfo = connectivityManager.getNetworkInfo(net);
                                        if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                                        //if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                                        Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                                        return true;
                                        }
                                        }
                                        } else {
                                        if (connectivityManager != null) {
                                        @SuppressWarnings("deprecation")
                                        NetworkInfo netInfoArray = connectivityManager.getAllNetworkInfo();
                                        if (netInfoArray != null) {
                                        for (NetworkInfo netInfo : netInfoArray) {
                                        if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                                        //if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
                                        Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                                        return true;
                                        }
                                        }
                                        }
                                        }
                                        }
                                        return false;
                                        }
                                        }





                                        share|improve this answer















                                        manifest:



                                        <receiver android:name=".your.namepackage.here.ConnectivityReceiver">
                                        <intent-filter>
                                        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                                        </intent-filter>
                                        </receiver>


                                        class for receiver:



                                        public class ConnectivityReceiver extends BroadcastReceiver{

                                        @Override
                                        public void onReceive(Context context, Intent intent) {
                                        final String action = intent.getAction();
                                        switch (action) {
                                        case ConnectivityManager.CONNECTIVITY_ACTION:
                                        DebugUtils.logDebug("BROADCAST", "network change");
                                        if(NetworkUtils.isConnect()){
                                        //do action here
                                        }
                                        break;
                                        }
                                        }
                                        }


                                        and classs utils like example:



                                        public class NetworkUtils {

                                        public static boolean isConnect() {
                                        ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        Network netArray = connectivityManager.getAllNetworks();
                                        NetworkInfo netInfo;
                                        for (Network net : netArray) {
                                        netInfo = connectivityManager.getNetworkInfo(net);
                                        if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                                        //if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                                        Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                                        return true;
                                        }
                                        }
                                        } else {
                                        if (connectivityManager != null) {
                                        @SuppressWarnings("deprecation")
                                        NetworkInfo netInfoArray = connectivityManager.getAllNetworkInfo();
                                        if (netInfoArray != null) {
                                        for (NetworkInfo netInfo : netInfoArray) {
                                        if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                                        //if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
                                        Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                                        return true;
                                        }
                                        }
                                        }
                                        }
                                        }
                                        return false;
                                        }
                                        }






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Aug 11 '16 at 23:41









                                        Paul Roub

                                        32.7k85773




                                        32.7k85773










                                        answered Aug 11 '16 at 23:31









                                        Alex ZaraosAlex Zaraos

                                        4,01911820




                                        4,01911820























                                            5














                                            CONNECTIVITY_ACTION docs:




                                            Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.







                                            share|improve this answer






























                                              5














                                              CONNECTIVITY_ACTION docs:




                                              Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.







                                              share|improve this answer




























                                                5












                                                5








                                                5







                                                CONNECTIVITY_ACTION docs:




                                                Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.







                                                share|improve this answer















                                                CONNECTIVITY_ACTION docs:




                                                Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.








                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Jul 5 '17 at 3:55









                                                Nathan Tuggy

                                                2,18892533




                                                2,18892533










                                                answered Jul 5 '17 at 3:32









                                                BJDMBJDM

                                                6124




                                                6124























                                                    4














                                                    just for someone else who wanna register a broadcast dynamicly:



                                                    BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
                                                    @Override
                                                    public void onReceive(Context context, Intent intent) {
                                                    if (checkWifiConnect()) {
                                                    Log.d(TAG, "wifi has connected");
                                                    // TODO
                                                    }
                                                    }
                                                    };

                                                    private void registerWifiReceiver() {
                                                    IntentFilter filter = new IntentFilter();
                                                    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                                                    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
                                                    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                                                    mContext.registerReceiver(mWifiReceiver, filter);
                                                    }

                                                    private void unregisterWifiReceiver() {
                                                    mContext.unregisterReceiver(mWifiReceiver);
                                                    }

                                                    private boolean checkWifiConnect() {
                                                    ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
                                                    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
                                                    if (networkInfo != null
                                                    && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                                                    && networkInfo.isConnected()) {
                                                    return true;
                                                    }
                                                    return false;
                                                    }





                                                    share|improve this answer




























                                                      4














                                                      just for someone else who wanna register a broadcast dynamicly:



                                                      BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
                                                      @Override
                                                      public void onReceive(Context context, Intent intent) {
                                                      if (checkWifiConnect()) {
                                                      Log.d(TAG, "wifi has connected");
                                                      // TODO
                                                      }
                                                      }
                                                      };

                                                      private void registerWifiReceiver() {
                                                      IntentFilter filter = new IntentFilter();
                                                      filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                                                      filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
                                                      filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                                                      mContext.registerReceiver(mWifiReceiver, filter);
                                                      }

                                                      private void unregisterWifiReceiver() {
                                                      mContext.unregisterReceiver(mWifiReceiver);
                                                      }

                                                      private boolean checkWifiConnect() {
                                                      ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
                                                      NetworkInfo networkInfo = manager.getActiveNetworkInfo();
                                                      if (networkInfo != null
                                                      && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                                                      && networkInfo.isConnected()) {
                                                      return true;
                                                      }
                                                      return false;
                                                      }





                                                      share|improve this answer


























                                                        4












                                                        4








                                                        4







                                                        just for someone else who wanna register a broadcast dynamicly:



                                                        BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
                                                        @Override
                                                        public void onReceive(Context context, Intent intent) {
                                                        if (checkWifiConnect()) {
                                                        Log.d(TAG, "wifi has connected");
                                                        // TODO
                                                        }
                                                        }
                                                        };

                                                        private void registerWifiReceiver() {
                                                        IntentFilter filter = new IntentFilter();
                                                        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                                                        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
                                                        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                                                        mContext.registerReceiver(mWifiReceiver, filter);
                                                        }

                                                        private void unregisterWifiReceiver() {
                                                        mContext.unregisterReceiver(mWifiReceiver);
                                                        }

                                                        private boolean checkWifiConnect() {
                                                        ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
                                                        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
                                                        if (networkInfo != null
                                                        && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                                                        && networkInfo.isConnected()) {
                                                        return true;
                                                        }
                                                        return false;
                                                        }





                                                        share|improve this answer













                                                        just for someone else who wanna register a broadcast dynamicly:



                                                        BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
                                                        @Override
                                                        public void onReceive(Context context, Intent intent) {
                                                        if (checkWifiConnect()) {
                                                        Log.d(TAG, "wifi has connected");
                                                        // TODO
                                                        }
                                                        }
                                                        };

                                                        private void registerWifiReceiver() {
                                                        IntentFilter filter = new IntentFilter();
                                                        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                                                        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
                                                        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                                                        mContext.registerReceiver(mWifiReceiver, filter);
                                                        }

                                                        private void unregisterWifiReceiver() {
                                                        mContext.unregisterReceiver(mWifiReceiver);
                                                        }

                                                        private boolean checkWifiConnect() {
                                                        ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
                                                        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
                                                        if (networkInfo != null
                                                        && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                                                        && networkInfo.isConnected()) {
                                                        return true;
                                                        }
                                                        return false;
                                                        }






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Mar 31 '17 at 5:34









                                                        li2li2

                                                        9901022




                                                        9901022























                                                            3














                                                            public class AsyncCheckInternet extends AsyncTask<String, Void, Boolean> {

                                                            public static final int TIME_OUT = 10 * 1000;

                                                            private OnCallBack listener;

                                                            public interface OnCallBack {

                                                            public void onBack(Boolean value);
                                                            }

                                                            public AsyncCheckInternet(OnCallBack listener) {
                                                            this.listener = listener;
                                                            }

                                                            @Override
                                                            protected void onPreExecute() {
                                                            }

                                                            @Override
                                                            protected Boolean doInBackground(String... params) {

                                                            ConnectivityManager connectivityManager = (ConnectivityManager) General.context
                                                            .getSystemService(Context.CONNECTIVITY_SERVICE);

                                                            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                                                            if ((networkInfo != null && networkInfo.isConnected())
                                                            && ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) || (networkInfo
                                                            .getType() == ConnectivityManager.TYPE_MOBILE))) {
                                                            HttpURLConnection urlc;
                                                            try {
                                                            urlc = (HttpURLConnection) (new URL("http://www.google.com")
                                                            .openConnection());
                                                            urlc.setConnectTimeout(TIME_OUT);
                                                            urlc.connect();
                                                            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                                            return true;
                                                            } else {
                                                            return false;
                                                            }
                                                            } catch (MalformedURLException e) {
                                                            e.printStackTrace();
                                                            return false;

                                                            } catch (IOException e) {
                                                            e.printStackTrace();
                                                            return false;

                                                            }
                                                            } else {
                                                            return false;
                                                            }
                                                            }

                                                            @Override
                                                            protected void onPostExecute(Boolean result) {
                                                            if (listener != null) {
                                                            listener.onBack(result);
                                                            }
                                                            }


                                                            }






                                                            share|improve this answer
























                                                            • AsynTasks should be used for something really small. You should use Service instead.

                                                              – TheLibrarian
                                                              Aug 28 '17 at 14:35
















                                                            3














                                                            public class AsyncCheckInternet extends AsyncTask<String, Void, Boolean> {

                                                            public static final int TIME_OUT = 10 * 1000;

                                                            private OnCallBack listener;

                                                            public interface OnCallBack {

                                                            public void onBack(Boolean value);
                                                            }

                                                            public AsyncCheckInternet(OnCallBack listener) {
                                                            this.listener = listener;
                                                            }

                                                            @Override
                                                            protected void onPreExecute() {
                                                            }

                                                            @Override
                                                            protected Boolean doInBackground(String... params) {

                                                            ConnectivityManager connectivityManager = (ConnectivityManager) General.context
                                                            .getSystemService(Context.CONNECTIVITY_SERVICE);

                                                            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                                                            if ((networkInfo != null && networkInfo.isConnected())
                                                            && ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) || (networkInfo
                                                            .getType() == ConnectivityManager.TYPE_MOBILE))) {
                                                            HttpURLConnection urlc;
                                                            try {
                                                            urlc = (HttpURLConnection) (new URL("http://www.google.com")
                                                            .openConnection());
                                                            urlc.setConnectTimeout(TIME_OUT);
                                                            urlc.connect();
                                                            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                                            return true;
                                                            } else {
                                                            return false;
                                                            }
                                                            } catch (MalformedURLException e) {
                                                            e.printStackTrace();
                                                            return false;

                                                            } catch (IOException e) {
                                                            e.printStackTrace();
                                                            return false;

                                                            }
                                                            } else {
                                                            return false;
                                                            }
                                                            }

                                                            @Override
                                                            protected void onPostExecute(Boolean result) {
                                                            if (listener != null) {
                                                            listener.onBack(result);
                                                            }
                                                            }


                                                            }






                                                            share|improve this answer
























                                                            • AsynTasks should be used for something really small. You should use Service instead.

                                                              – TheLibrarian
                                                              Aug 28 '17 at 14:35














                                                            3












                                                            3








                                                            3







                                                            public class AsyncCheckInternet extends AsyncTask<String, Void, Boolean> {

                                                            public static final int TIME_OUT = 10 * 1000;

                                                            private OnCallBack listener;

                                                            public interface OnCallBack {

                                                            public void onBack(Boolean value);
                                                            }

                                                            public AsyncCheckInternet(OnCallBack listener) {
                                                            this.listener = listener;
                                                            }

                                                            @Override
                                                            protected void onPreExecute() {
                                                            }

                                                            @Override
                                                            protected Boolean doInBackground(String... params) {

                                                            ConnectivityManager connectivityManager = (ConnectivityManager) General.context
                                                            .getSystemService(Context.CONNECTIVITY_SERVICE);

                                                            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                                                            if ((networkInfo != null && networkInfo.isConnected())
                                                            && ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) || (networkInfo
                                                            .getType() == ConnectivityManager.TYPE_MOBILE))) {
                                                            HttpURLConnection urlc;
                                                            try {
                                                            urlc = (HttpURLConnection) (new URL("http://www.google.com")
                                                            .openConnection());
                                                            urlc.setConnectTimeout(TIME_OUT);
                                                            urlc.connect();
                                                            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                                            return true;
                                                            } else {
                                                            return false;
                                                            }
                                                            } catch (MalformedURLException e) {
                                                            e.printStackTrace();
                                                            return false;

                                                            } catch (IOException e) {
                                                            e.printStackTrace();
                                                            return false;

                                                            }
                                                            } else {
                                                            return false;
                                                            }
                                                            }

                                                            @Override
                                                            protected void onPostExecute(Boolean result) {
                                                            if (listener != null) {
                                                            listener.onBack(result);
                                                            }
                                                            }


                                                            }






                                                            share|improve this answer













                                                            public class AsyncCheckInternet extends AsyncTask<String, Void, Boolean> {

                                                            public static final int TIME_OUT = 10 * 1000;

                                                            private OnCallBack listener;

                                                            public interface OnCallBack {

                                                            public void onBack(Boolean value);
                                                            }

                                                            public AsyncCheckInternet(OnCallBack listener) {
                                                            this.listener = listener;
                                                            }

                                                            @Override
                                                            protected void onPreExecute() {
                                                            }

                                                            @Override
                                                            protected Boolean doInBackground(String... params) {

                                                            ConnectivityManager connectivityManager = (ConnectivityManager) General.context
                                                            .getSystemService(Context.CONNECTIVITY_SERVICE);

                                                            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                                                            if ((networkInfo != null && networkInfo.isConnected())
                                                            && ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) || (networkInfo
                                                            .getType() == ConnectivityManager.TYPE_MOBILE))) {
                                                            HttpURLConnection urlc;
                                                            try {
                                                            urlc = (HttpURLConnection) (new URL("http://www.google.com")
                                                            .openConnection());
                                                            urlc.setConnectTimeout(TIME_OUT);
                                                            urlc.connect();
                                                            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                                            return true;
                                                            } else {
                                                            return false;
                                                            }
                                                            } catch (MalformedURLException e) {
                                                            e.printStackTrace();
                                                            return false;

                                                            } catch (IOException e) {
                                                            e.printStackTrace();
                                                            return false;

                                                            }
                                                            } else {
                                                            return false;
                                                            }
                                                            }

                                                            @Override
                                                            protected void onPostExecute(Boolean result) {
                                                            if (listener != null) {
                                                            listener.onBack(result);
                                                            }
                                                            }


                                                            }







                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Dec 24 '15 at 9:51









                                                            Farzad RohaniFarzad Rohani

                                                            313




                                                            313













                                                            • AsynTasks should be used for something really small. You should use Service instead.

                                                              – TheLibrarian
                                                              Aug 28 '17 at 14:35



















                                                            • AsynTasks should be used for something really small. You should use Service instead.

                                                              – TheLibrarian
                                                              Aug 28 '17 at 14:35

















                                                            AsynTasks should be used for something really small. You should use Service instead.

                                                            – TheLibrarian
                                                            Aug 28 '17 at 14:35





                                                            AsynTasks should be used for something really small. You should use Service instead.

                                                            – TheLibrarian
                                                            Aug 28 '17 at 14:35











                                                            3














                                                            Add a broadcast receiver which can listen to network connectivity change. Then check wether device is connected to internet or not using ConnectivityManager. Refer to this post or video for detailed understanding. Below is the code:



                                                            public class NetworkStateChangeReceiver extends BroadcastReceiver {
                                                            public static final String NETWORK_AVAILABLE_ACTION = "com.ajit.singh.NetworkAvailable";
                                                            public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";

                                                            @Override
                                                            public void onReceive(Context context, Intent intent) {
                                                            Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
                                                            networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
                                                            LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
                                                            }

                                                            private boolean isConnectedToInternet(Context context) {
                                                            try {
                                                            if (context != null) {
                                                            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
                                                            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                                                            return networkInfo != null && networkInfo.isConnected();
                                                            }
                                                            return false;
                                                            } catch (Exception e) {
                                                            Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
                                                            return false;
                                                            }
                                                            }
                                                            }


                                                            I wrote this receiver to show a notification on the Screen, that's why you see a local broadcast with the network status. Here is the code to show the notification.



                                                            public class MainActivity extends AppCompatActivity {

                                                            @Override
                                                            protected void onCreate(Bundle savedInstanceState) {
                                                            super.onCreate(savedInstanceState);
                                                            setContentView(R.layout.activity_main);

                                                            IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
                                                            LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
                                                            @Override
                                                            public void onReceive(Context context, Intent intent) {
                                                            boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
                                                            String networkStatus = isNetworkAvailable ? "connected" : "disconnected";

                                                            Snackbar.make(findViewById(R.id.activity_main), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
                                                            }
                                                            }, intentFilter);
                                                            }
                                                            }


                                                            Activity listens to the intent broadcasted by the network receiver and shows the notification on the screen.






                                                            share|improve this answer




























                                                              3














                                                              Add a broadcast receiver which can listen to network connectivity change. Then check wether device is connected to internet or not using ConnectivityManager. Refer to this post or video for detailed understanding. Below is the code:



                                                              public class NetworkStateChangeReceiver extends BroadcastReceiver {
                                                              public static final String NETWORK_AVAILABLE_ACTION = "com.ajit.singh.NetworkAvailable";
                                                              public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";

                                                              @Override
                                                              public void onReceive(Context context, Intent intent) {
                                                              Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
                                                              networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
                                                              LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
                                                              }

                                                              private boolean isConnectedToInternet(Context context) {
                                                              try {
                                                              if (context != null) {
                                                              ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
                                                              NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                                                              return networkInfo != null && networkInfo.isConnected();
                                                              }
                                                              return false;
                                                              } catch (Exception e) {
                                                              Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
                                                              return false;
                                                              }
                                                              }
                                                              }


                                                              I wrote this receiver to show a notification on the Screen, that's why you see a local broadcast with the network status. Here is the code to show the notification.



                                                              public class MainActivity extends AppCompatActivity {

                                                              @Override
                                                              protected void onCreate(Bundle savedInstanceState) {
                                                              super.onCreate(savedInstanceState);
                                                              setContentView(R.layout.activity_main);

                                                              IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
                                                              LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
                                                              @Override
                                                              public void onReceive(Context context, Intent intent) {
                                                              boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
                                                              String networkStatus = isNetworkAvailable ? "connected" : "disconnected";

                                                              Snackbar.make(findViewById(R.id.activity_main), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
                                                              }
                                                              }, intentFilter);
                                                              }
                                                              }


                                                              Activity listens to the intent broadcasted by the network receiver and shows the notification on the screen.






                                                              share|improve this answer


























                                                                3












                                                                3








                                                                3







                                                                Add a broadcast receiver which can listen to network connectivity change. Then check wether device is connected to internet or not using ConnectivityManager. Refer to this post or video for detailed understanding. Below is the code:



                                                                public class NetworkStateChangeReceiver extends BroadcastReceiver {
                                                                public static final String NETWORK_AVAILABLE_ACTION = "com.ajit.singh.NetworkAvailable";
                                                                public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";

                                                                @Override
                                                                public void onReceive(Context context, Intent intent) {
                                                                Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
                                                                networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
                                                                LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
                                                                }

                                                                private boolean isConnectedToInternet(Context context) {
                                                                try {
                                                                if (context != null) {
                                                                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
                                                                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                                                                return networkInfo != null && networkInfo.isConnected();
                                                                }
                                                                return false;
                                                                } catch (Exception e) {
                                                                Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
                                                                return false;
                                                                }
                                                                }
                                                                }


                                                                I wrote this receiver to show a notification on the Screen, that's why you see a local broadcast with the network status. Here is the code to show the notification.



                                                                public class MainActivity extends AppCompatActivity {

                                                                @Override
                                                                protected void onCreate(Bundle savedInstanceState) {
                                                                super.onCreate(savedInstanceState);
                                                                setContentView(R.layout.activity_main);

                                                                IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
                                                                LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
                                                                @Override
                                                                public void onReceive(Context context, Intent intent) {
                                                                boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
                                                                String networkStatus = isNetworkAvailable ? "connected" : "disconnected";

                                                                Snackbar.make(findViewById(R.id.activity_main), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
                                                                }
                                                                }, intentFilter);
                                                                }
                                                                }


                                                                Activity listens to the intent broadcasted by the network receiver and shows the notification on the screen.






                                                                share|improve this answer













                                                                Add a broadcast receiver which can listen to network connectivity change. Then check wether device is connected to internet or not using ConnectivityManager. Refer to this post or video for detailed understanding. Below is the code:



                                                                public class NetworkStateChangeReceiver extends BroadcastReceiver {
                                                                public static final String NETWORK_AVAILABLE_ACTION = "com.ajit.singh.NetworkAvailable";
                                                                public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";

                                                                @Override
                                                                public void onReceive(Context context, Intent intent) {
                                                                Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
                                                                networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
                                                                LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
                                                                }

                                                                private boolean isConnectedToInternet(Context context) {
                                                                try {
                                                                if (context != null) {
                                                                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
                                                                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                                                                return networkInfo != null && networkInfo.isConnected();
                                                                }
                                                                return false;
                                                                } catch (Exception e) {
                                                                Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
                                                                return false;
                                                                }
                                                                }
                                                                }


                                                                I wrote this receiver to show a notification on the Screen, that's why you see a local broadcast with the network status. Here is the code to show the notification.



                                                                public class MainActivity extends AppCompatActivity {

                                                                @Override
                                                                protected void onCreate(Bundle savedInstanceState) {
                                                                super.onCreate(savedInstanceState);
                                                                setContentView(R.layout.activity_main);

                                                                IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
                                                                LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
                                                                @Override
                                                                public void onReceive(Context context, Intent intent) {
                                                                boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
                                                                String networkStatus = isNetworkAvailable ? "connected" : "disconnected";

                                                                Snackbar.make(findViewById(R.id.activity_main), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
                                                                }
                                                                }, intentFilter);
                                                                }
                                                                }


                                                                Activity listens to the intent broadcasted by the network receiver and shows the notification on the screen.







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Oct 28 '16 at 14:49









                                                                Ajit SinghAjit Singh

                                                                1,7051522




                                                                1,7051522























                                                                    2














                                                                    Here's a comfortable way to do it for activity, fragment or context. It will also auto-unregister if you do it for activity/fragment (in onDestroy), if you wish:



                                                                    abstract class ConnectionBroadcastReceiver : BroadcastReceiver() {
                                                                    companion object {
                                                                    @JvmStatic
                                                                    fun registerWithoutAutoUnregister(context: Context, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                    context.registerReceiver(connectionBroadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
                                                                    }

                                                                    @JvmStatic
                                                                    fun registerToFragmentAndAutoUnregister(context: Context, fragment: Fragment, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                    val applicationContext = context.applicationContext
                                                                    registerWithoutAutoUnregister(applicationContext, connectionBroadcastReceiver)
                                                                    fragment.lifecycle.addObserver(object : LifecycleObserver {
                                                                    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                                                                    fun onDestroy() {
                                                                    applicationContext.unregisterReceiver(connectionBroadcastReceiver)
                                                                    }
                                                                    })
                                                                    }

                                                                    @JvmStatic
                                                                    fun registerToActivityAndAutoUnregister(activity: AppCompatActivity, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                    registerWithoutAutoUnregister(activity, connectionBroadcastReceiver)
                                                                    activity.lifecycle.addObserver(object : LifecycleObserver {
                                                                    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                                                                    fun onDestroy() {
                                                                    activity.unregisterReceiver(connectionBroadcastReceiver)
                                                                    }
                                                                    })
                                                                    }

                                                                    @JvmStatic
                                                                    fun hasInternetConnection(context: Context): Boolean {
                                                                    val info = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
                                                                    return !(info == null || !info.isConnectedOrConnecting)
                                                                    }
                                                                    }

                                                                    override fun onReceive(context: Context, intent: Intent) {
                                                                    val hasConnection = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
                                                                    // Log.d("AppLog", "conenctivity changed. hasConnection? $hasConnection")
                                                                    onConnectionChanged(hasConnection)
                                                                    }

                                                                    abstract fun onConnectionChanged(hasConnection: Boolean)
                                                                    }


                                                                    Usage in fragment:



                                                                        ConnectionBroadcastReceiver.registerToFragmentAndAutoUnregister(activity!!, this, object : ConnectionBroadcastReceiver() {
                                                                    override fun onConnectionChanged(hasConnection: Boolean) {
                                                                    // Log.d("AppLog", "onConnectionChanged:" + hasConnection)
                                                                    }
                                                                    })





                                                                    share|improve this answer






























                                                                      2














                                                                      Here's a comfortable way to do it for activity, fragment or context. It will also auto-unregister if you do it for activity/fragment (in onDestroy), if you wish:



                                                                      abstract class ConnectionBroadcastReceiver : BroadcastReceiver() {
                                                                      companion object {
                                                                      @JvmStatic
                                                                      fun registerWithoutAutoUnregister(context: Context, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                      context.registerReceiver(connectionBroadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
                                                                      }

                                                                      @JvmStatic
                                                                      fun registerToFragmentAndAutoUnregister(context: Context, fragment: Fragment, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                      val applicationContext = context.applicationContext
                                                                      registerWithoutAutoUnregister(applicationContext, connectionBroadcastReceiver)
                                                                      fragment.lifecycle.addObserver(object : LifecycleObserver {
                                                                      @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                                                                      fun onDestroy() {
                                                                      applicationContext.unregisterReceiver(connectionBroadcastReceiver)
                                                                      }
                                                                      })
                                                                      }

                                                                      @JvmStatic
                                                                      fun registerToActivityAndAutoUnregister(activity: AppCompatActivity, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                      registerWithoutAutoUnregister(activity, connectionBroadcastReceiver)
                                                                      activity.lifecycle.addObserver(object : LifecycleObserver {
                                                                      @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                                                                      fun onDestroy() {
                                                                      activity.unregisterReceiver(connectionBroadcastReceiver)
                                                                      }
                                                                      })
                                                                      }

                                                                      @JvmStatic
                                                                      fun hasInternetConnection(context: Context): Boolean {
                                                                      val info = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
                                                                      return !(info == null || !info.isConnectedOrConnecting)
                                                                      }
                                                                      }

                                                                      override fun onReceive(context: Context, intent: Intent) {
                                                                      val hasConnection = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
                                                                      // Log.d("AppLog", "conenctivity changed. hasConnection? $hasConnection")
                                                                      onConnectionChanged(hasConnection)
                                                                      }

                                                                      abstract fun onConnectionChanged(hasConnection: Boolean)
                                                                      }


                                                                      Usage in fragment:



                                                                          ConnectionBroadcastReceiver.registerToFragmentAndAutoUnregister(activity!!, this, object : ConnectionBroadcastReceiver() {
                                                                      override fun onConnectionChanged(hasConnection: Boolean) {
                                                                      // Log.d("AppLog", "onConnectionChanged:" + hasConnection)
                                                                      }
                                                                      })





                                                                      share|improve this answer




























                                                                        2












                                                                        2








                                                                        2







                                                                        Here's a comfortable way to do it for activity, fragment or context. It will also auto-unregister if you do it for activity/fragment (in onDestroy), if you wish:



                                                                        abstract class ConnectionBroadcastReceiver : BroadcastReceiver() {
                                                                        companion object {
                                                                        @JvmStatic
                                                                        fun registerWithoutAutoUnregister(context: Context, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                        context.registerReceiver(connectionBroadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
                                                                        }

                                                                        @JvmStatic
                                                                        fun registerToFragmentAndAutoUnregister(context: Context, fragment: Fragment, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                        val applicationContext = context.applicationContext
                                                                        registerWithoutAutoUnregister(applicationContext, connectionBroadcastReceiver)
                                                                        fragment.lifecycle.addObserver(object : LifecycleObserver {
                                                                        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                                                                        fun onDestroy() {
                                                                        applicationContext.unregisterReceiver(connectionBroadcastReceiver)
                                                                        }
                                                                        })
                                                                        }

                                                                        @JvmStatic
                                                                        fun registerToActivityAndAutoUnregister(activity: AppCompatActivity, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                        registerWithoutAutoUnregister(activity, connectionBroadcastReceiver)
                                                                        activity.lifecycle.addObserver(object : LifecycleObserver {
                                                                        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                                                                        fun onDestroy() {
                                                                        activity.unregisterReceiver(connectionBroadcastReceiver)
                                                                        }
                                                                        })
                                                                        }

                                                                        @JvmStatic
                                                                        fun hasInternetConnection(context: Context): Boolean {
                                                                        val info = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
                                                                        return !(info == null || !info.isConnectedOrConnecting)
                                                                        }
                                                                        }

                                                                        override fun onReceive(context: Context, intent: Intent) {
                                                                        val hasConnection = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
                                                                        // Log.d("AppLog", "conenctivity changed. hasConnection? $hasConnection")
                                                                        onConnectionChanged(hasConnection)
                                                                        }

                                                                        abstract fun onConnectionChanged(hasConnection: Boolean)
                                                                        }


                                                                        Usage in fragment:



                                                                            ConnectionBroadcastReceiver.registerToFragmentAndAutoUnregister(activity!!, this, object : ConnectionBroadcastReceiver() {
                                                                        override fun onConnectionChanged(hasConnection: Boolean) {
                                                                        // Log.d("AppLog", "onConnectionChanged:" + hasConnection)
                                                                        }
                                                                        })





                                                                        share|improve this answer















                                                                        Here's a comfortable way to do it for activity, fragment or context. It will also auto-unregister if you do it for activity/fragment (in onDestroy), if you wish:



                                                                        abstract class ConnectionBroadcastReceiver : BroadcastReceiver() {
                                                                        companion object {
                                                                        @JvmStatic
                                                                        fun registerWithoutAutoUnregister(context: Context, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                        context.registerReceiver(connectionBroadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
                                                                        }

                                                                        @JvmStatic
                                                                        fun registerToFragmentAndAutoUnregister(context: Context, fragment: Fragment, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                        val applicationContext = context.applicationContext
                                                                        registerWithoutAutoUnregister(applicationContext, connectionBroadcastReceiver)
                                                                        fragment.lifecycle.addObserver(object : LifecycleObserver {
                                                                        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                                                                        fun onDestroy() {
                                                                        applicationContext.unregisterReceiver(connectionBroadcastReceiver)
                                                                        }
                                                                        })
                                                                        }

                                                                        @JvmStatic
                                                                        fun registerToActivityAndAutoUnregister(activity: AppCompatActivity, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
                                                                        registerWithoutAutoUnregister(activity, connectionBroadcastReceiver)
                                                                        activity.lifecycle.addObserver(object : LifecycleObserver {
                                                                        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                                                                        fun onDestroy() {
                                                                        activity.unregisterReceiver(connectionBroadcastReceiver)
                                                                        }
                                                                        })
                                                                        }

                                                                        @JvmStatic
                                                                        fun hasInternetConnection(context: Context): Boolean {
                                                                        val info = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
                                                                        return !(info == null || !info.isConnectedOrConnecting)
                                                                        }
                                                                        }

                                                                        override fun onReceive(context: Context, intent: Intent) {
                                                                        val hasConnection = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
                                                                        // Log.d("AppLog", "conenctivity changed. hasConnection? $hasConnection")
                                                                        onConnectionChanged(hasConnection)
                                                                        }

                                                                        abstract fun onConnectionChanged(hasConnection: Boolean)
                                                                        }


                                                                        Usage in fragment:



                                                                            ConnectionBroadcastReceiver.registerToFragmentAndAutoUnregister(activity!!, this, object : ConnectionBroadcastReceiver() {
                                                                        override fun onConnectionChanged(hasConnection: Boolean) {
                                                                        // Log.d("AppLog", "onConnectionChanged:" + hasConnection)
                                                                        }
                                                                        })






                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited Apr 12 '18 at 10:20

























                                                                        answered Apr 11 '18 at 12:07









                                                                        android developerandroid developer

                                                                        55.2k98465857




                                                                        55.2k98465857























                                                                            1














                                                                            Broadcast receiver code to check internet connectivity change:



                                                                            public class BroadCastDetecter extends BroadcastReceiver {
                                                                            public static boolean internet_status = false;
                                                                            public static void checkInternetConenction(Context context) {
                                                                            internet_status = false;
                                                                            ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                                                                            if (check != null) {
                                                                            NetworkInfo info = check.getAllNetworkInfo();
                                                                            if (info != null)
                                                                            for (int i = 0; i < info.length; i++)
                                                                            {
                                                                            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                                                                            internet_status = true;
                                                                            }
                                                                            }
                                                                            if(internet_status)
                                                                            {
                                                                            //do what you want to if internet connection is available
                                                                            }
                                                                            }
                                                                            }

                                                                            @Override
                                                                            public void onReceive(Context context, Intent intent)
                                                                            {
                                                                            try {
                                                                            checkInternetConenction(context);
                                                                            }catch(Exception e){

                                                                            }
                                                                            }
                                                                            }


                                                                            add this in manifest file:



                                                                             <receiver android:name=".BroadCastDetecter">
                                                                            <intent-filter>
                                                                            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                                                                            </intent-filter>
                                                                            </receiver>





                                                                            share|improve this answer




























                                                                              1














                                                                              Broadcast receiver code to check internet connectivity change:



                                                                              public class BroadCastDetecter extends BroadcastReceiver {
                                                                              public static boolean internet_status = false;
                                                                              public static void checkInternetConenction(Context context) {
                                                                              internet_status = false;
                                                                              ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                                                                              if (check != null) {
                                                                              NetworkInfo info = check.getAllNetworkInfo();
                                                                              if (info != null)
                                                                              for (int i = 0; i < info.length; i++)
                                                                              {
                                                                              if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                                                                              internet_status = true;
                                                                              }
                                                                              }
                                                                              if(internet_status)
                                                                              {
                                                                              //do what you want to if internet connection is available
                                                                              }
                                                                              }
                                                                              }

                                                                              @Override
                                                                              public void onReceive(Context context, Intent intent)
                                                                              {
                                                                              try {
                                                                              checkInternetConenction(context);
                                                                              }catch(Exception e){

                                                                              }
                                                                              }
                                                                              }


                                                                              add this in manifest file:



                                                                               <receiver android:name=".BroadCastDetecter">
                                                                              <intent-filter>
                                                                              <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                                                                              </intent-filter>
                                                                              </receiver>





                                                                              share|improve this answer


























                                                                                1












                                                                                1








                                                                                1







                                                                                Broadcast receiver code to check internet connectivity change:



                                                                                public class BroadCastDetecter extends BroadcastReceiver {
                                                                                public static boolean internet_status = false;
                                                                                public static void checkInternetConenction(Context context) {
                                                                                internet_status = false;
                                                                                ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                                                                                if (check != null) {
                                                                                NetworkInfo info = check.getAllNetworkInfo();
                                                                                if (info != null)
                                                                                for (int i = 0; i < info.length; i++)
                                                                                {
                                                                                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                                                                                internet_status = true;
                                                                                }
                                                                                }
                                                                                if(internet_status)
                                                                                {
                                                                                //do what you want to if internet connection is available
                                                                                }
                                                                                }
                                                                                }

                                                                                @Override
                                                                                public void onReceive(Context context, Intent intent)
                                                                                {
                                                                                try {
                                                                                checkInternetConenction(context);
                                                                                }catch(Exception e){

                                                                                }
                                                                                }
                                                                                }


                                                                                add this in manifest file:



                                                                                 <receiver android:name=".BroadCastDetecter">
                                                                                <intent-filter>
                                                                                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                                                                                </intent-filter>
                                                                                </receiver>





                                                                                share|improve this answer













                                                                                Broadcast receiver code to check internet connectivity change:



                                                                                public class BroadCastDetecter extends BroadcastReceiver {
                                                                                public static boolean internet_status = false;
                                                                                public static void checkInternetConenction(Context context) {
                                                                                internet_status = false;
                                                                                ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                                                                                if (check != null) {
                                                                                NetworkInfo info = check.getAllNetworkInfo();
                                                                                if (info != null)
                                                                                for (int i = 0; i < info.length; i++)
                                                                                {
                                                                                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                                                                                internet_status = true;
                                                                                }
                                                                                }
                                                                                if(internet_status)
                                                                                {
                                                                                //do what you want to if internet connection is available
                                                                                }
                                                                                }
                                                                                }

                                                                                @Override
                                                                                public void onReceive(Context context, Intent intent)
                                                                                {
                                                                                try {
                                                                                checkInternetConenction(context);
                                                                                }catch(Exception e){

                                                                                }
                                                                                }
                                                                                }


                                                                                add this in manifest file:



                                                                                 <receiver android:name=".BroadCastDetecter">
                                                                                <intent-filter>
                                                                                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                                                                                </intent-filter>
                                                                                </receiver>






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Sep 15 '17 at 6:49









                                                                                Bapusaheb ShindeBapusaheb Shinde

                                                                                5761714




                                                                                5761714























                                                                                    -1














                                                                                    First of all we will make a class that will check the connectivity of the network state. So lets create a class :



                                                                                    public class AppStatus {
                                                                                    private static AppStatus instance = new AppStatus();
                                                                                    static Context context;
                                                                                    ConnectivityManager connectivityManager;
                                                                                    NetworkInfo wifiInfo, mobileInfo;
                                                                                    boolean connected = false;

                                                                                    public static AppStatus getInstance(Context ctx) {
                                                                                    context = ctx.getApplicationContext();
                                                                                    return instance;
                                                                                    }

                                                                                    public boolean isOnline() {
                                                                                    try {
                                                                                    connectivityManager = (ConnectivityManager) context
                                                                                    .getSystemService(Context.CONNECTIVITY_SERVICE);

                                                                                    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                                                                                    connected = networkInfo != null && networkInfo.isAvailable() &&
                                                                                    networkInfo.isConnected();
                                                                                    return connected;


                                                                                    } catch (Exception e) {
                                                                                    System.out.println("CheckConnectivity Exception: " + e.getMessage());
                                                                                    Log.v("connectivity", e.toString());
                                                                                    }
                                                                                    return connected;
                                                                                    }
                                                                                    }


                                                                                    Now Make a new Broadcast receiver class :



                                                                                    public class ConnectivityReceiver extends BroadcastReceiver {
                                                                                    @Override
                                                                                    public void onReceive(Context context, Intent intent) {
                                                                                    if (AppStatus.getInstance(context).isOnline()) {

                                                                                    Intent intent1=new Intent(context,DisplayAct.class);
                                                                                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                                                    context.startActivity(intent1);




                                                                                    } else {

                                                                                    Toast.makeText(context, "Please !! Make your network ON", Toast.LENGTH_SHORT).show();

                                                                                    }
                                                                                    }
                                                                                    }


                                                                                    and Now register your broadcast receiver on manifest:



                                                                                    <receiver android:name=".ConnectivityReceiver">
                                                                                    <intent-filter>
                                                                                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                                                                                    </intent-filter>
                                                                                    </receiver>





                                                                                    share|improve this answer




























                                                                                      -1














                                                                                      First of all we will make a class that will check the connectivity of the network state. So lets create a class :



                                                                                      public class AppStatus {
                                                                                      private static AppStatus instance = new AppStatus();
                                                                                      static Context context;
                                                                                      ConnectivityManager connectivityManager;
                                                                                      NetworkInfo wifiInfo, mobileInfo;
                                                                                      boolean connected = false;

                                                                                      public static AppStatus getInstance(Context ctx) {
                                                                                      context = ctx.getApplicationContext();
                                                                                      return instance;
                                                                                      }

                                                                                      public boolean isOnline() {
                                                                                      try {
                                                                                      connectivityManager = (ConnectivityManager) context
                                                                                      .getSystemService(Context.CONNECTIVITY_SERVICE);

                                                                                      NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                                                                                      connected = networkInfo != null && networkInfo.isAvailable() &&
                                                                                      networkInfo.isConnected();
                                                                                      return connected;


                                                                                      } catch (Exception e) {
                                                                                      System.out.println("CheckConnectivity Exception: " + e.getMessage());
                                                                                      Log.v("connectivity", e.toString());
                                                                                      }
                                                                                      return connected;
                                                                                      }
                                                                                      }


                                                                                      Now Make a new Broadcast receiver class :



                                                                                      public class ConnectivityReceiver extends BroadcastReceiver {
                                                                                      @Override
                                                                                      public void onReceive(Context context, Intent intent) {
                                                                                      if (AppStatus.getInstance(context).isOnline()) {

                                                                                      Intent intent1=new Intent(context,DisplayAct.class);
                                                                                      intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                                                      context.startActivity(intent1);




                                                                                      } else {

                                                                                      Toast.makeText(context, "Please !! Make your network ON", Toast.LENGTH_SHORT).show();

                                                                                      }
                                                                                      }
                                                                                      }


                                                                                      and Now register your broadcast receiver on manifest:



                                                                                      <receiver android:name=".ConnectivityReceiver">
                                                                                      <intent-filter>
                                                                                      <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                                                                                      </intent-filter>
                                                                                      </receiver>





                                                                                      share|improve this answer


























                                                                                        -1












                                                                                        -1








                                                                                        -1







                                                                                        First of all we will make a class that will check the connectivity of the network state. So lets create a class :



                                                                                        public class AppStatus {
                                                                                        private static AppStatus instance = new AppStatus();
                                                                                        static Context context;
                                                                                        ConnectivityManager connectivityManager;
                                                                                        NetworkInfo wifiInfo, mobileInfo;
                                                                                        boolean connected = false;

                                                                                        public static AppStatus getInstance(Context ctx) {
                                                                                        context = ctx.getApplicationContext();
                                                                                        return instance;
                                                                                        }

                                                                                        public boolean isOnline() {
                                                                                        try {
                                                                                        connectivityManager = (ConnectivityManager) context
                                                                                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                                                                                        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                                                                                        connected = networkInfo != null && networkInfo.isAvailable() &&
                                                                                        networkInfo.isConnected();
                                                                                        return connected;


                                                                                        } catch (Exception e) {
                                                                                        System.out.println("CheckConnectivity Exception: " + e.getMessage());
                                                                                        Log.v("connectivity", e.toString());
                                                                                        }
                                                                                        return connected;
                                                                                        }
                                                                                        }


                                                                                        Now Make a new Broadcast receiver class :



                                                                                        public class ConnectivityReceiver extends BroadcastReceiver {
                                                                                        @Override
                                                                                        public void onReceive(Context context, Intent intent) {
                                                                                        if (AppStatus.getInstance(context).isOnline()) {

                                                                                        Intent intent1=new Intent(context,DisplayAct.class);
                                                                                        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                                                        context.startActivity(intent1);




                                                                                        } else {

                                                                                        Toast.makeText(context, "Please !! Make your network ON", Toast.LENGTH_SHORT).show();

                                                                                        }
                                                                                        }
                                                                                        }


                                                                                        and Now register your broadcast receiver on manifest:



                                                                                        <receiver android:name=".ConnectivityReceiver">
                                                                                        <intent-filter>
                                                                                        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                                                                                        </intent-filter>
                                                                                        </receiver>





                                                                                        share|improve this answer













                                                                                        First of all we will make a class that will check the connectivity of the network state. So lets create a class :



                                                                                        public class AppStatus {
                                                                                        private static AppStatus instance = new AppStatus();
                                                                                        static Context context;
                                                                                        ConnectivityManager connectivityManager;
                                                                                        NetworkInfo wifiInfo, mobileInfo;
                                                                                        boolean connected = false;

                                                                                        public static AppStatus getInstance(Context ctx) {
                                                                                        context = ctx.getApplicationContext();
                                                                                        return instance;
                                                                                        }

                                                                                        public boolean isOnline() {
                                                                                        try {
                                                                                        connectivityManager = (ConnectivityManager) context
                                                                                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                                                                                        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                                                                                        connected = networkInfo != null && networkInfo.isAvailable() &&
                                                                                        networkInfo.isConnected();
                                                                                        return connected;


                                                                                        } catch (Exception e) {
                                                                                        System.out.println("CheckConnectivity Exception: " + e.getMessage());
                                                                                        Log.v("connectivity", e.toString());
                                                                                        }
                                                                                        return connected;
                                                                                        }
                                                                                        }


                                                                                        Now Make a new Broadcast receiver class :



                                                                                        public class ConnectivityReceiver extends BroadcastReceiver {
                                                                                        @Override
                                                                                        public void onReceive(Context context, Intent intent) {
                                                                                        if (AppStatus.getInstance(context).isOnline()) {

                                                                                        Intent intent1=new Intent(context,DisplayAct.class);
                                                                                        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                                                        context.startActivity(intent1);




                                                                                        } else {

                                                                                        Toast.makeText(context, "Please !! Make your network ON", Toast.LENGTH_SHORT).show();

                                                                                        }
                                                                                        }
                                                                                        }


                                                                                        and Now register your broadcast receiver on manifest:



                                                                                        <receiver android:name=".ConnectivityReceiver">
                                                                                        <intent-filter>
                                                                                        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
                                                                                        </intent-filter>
                                                                                        </receiver>






                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Aug 11 '18 at 9:39









                                                                                        Pradeep SheoranPradeep Sheoran

                                                                                        14810




                                                                                        14810















                                                                                            Popular posts from this blog

                                                                                            Xamarin.iOS Cant Deploy on Iphone

                                                                                            Glorious Revolution

                                                                                            Dulmage-Mendelsohn matrix decomposition in Python