I have Broadcast Receiver for doing Internet checking. Every time device is not connected with Internet, always getting 2 output. I just want one output.
BroadcastReceiver
public class Broadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected){
Log.i("INTERNET","------------------------- not connect");
}
}
}
And this is the output
12659-12659 I/ViewRootImpl: CPU Rendering VSync enable = true
12659-12659 I/ViewRootImpl: CPU Rendering VSync enable = true
12659-12701 V/RenderScript: Application requested CPU execution
12659-12701 V/RenderScript: 0xb8116c40 Launching thread(s), CPUs 4
12659-12659 I/INTERNET: ------------------------- not connect
12659-12659 I/INTERNET: ------------------------- not connect
try this
create one class
public class ConnectivityReceiver extends BroadcastReceiver {
public static ConnectivityReceiverListener connectivityReceiverListener;
public ConnectivityReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent arg1) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
}
}
public static boolean isConnected() {
ConnectivityManager
cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
create one another class
public class MyApplication extends Application {
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
add permisiion in maenfiest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
**and this **
**
and dont forget to add this in manifiest
<receiver
android:name="com.ncrypted.redfox.Utils.ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
now call the where you want to check internet like this
implement this in your activity
ConnectivityReceiver.ConnectivityReceiverListener
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}
private void showSnack(boolean isConnected) {
if (isConnected) {
getUserStatus();
} else {
Toast.makeText(this, getString(R.string.str_internet_err), Toast.LENGTH_SHORT).show();
}
}
for more information please follow this link
You can check Network availability without Broadcast Receiver.
public class ConnectivityUtils {
private final Activity mActivity;
public ConnectivityUtils(Activity mActivity) {
this.mActivity = mActivity;
}
public boolean getConnectivityStatus() {
ConnectivityManager cm = (ConnectivityManager) mActivity
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return null != activeNetwork;
}
}
Add in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Related
I want to check whether Internet connection is turned on or not when app starts. It should allow to start if internet is connected. Else display a error message and direct user to settings. Message need to be displayed until Internet connection is turned on.
Already I finished connection check function and alert display function. How could I listen whether internet is turned on or not after user directed to settings
connection check function is,
public boolean connectionIsAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
and alert display,
public void displayAlertDialog(final Context context){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_TRADITIONAL);
alertDialogBuilder.setMessage("Would you like to enable it?")
.setTitle("No Internet Connection")
.setPositiveButton(" Enable Internet ", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dialogIntent);
}
});
alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
In my onCreate I check like,
if(connectionIsAvailable(getApplicationContext())) {
welcomeThread.start();
} else {
displayAlertDialog(LoadingScreenActivity.this);
}
Help me how could I listen whether internet is turned on or not after user directed to settings. Thanks in advance.
Register receiver in manifest file
<!-- Broadcast receiver declaration in manifest file and make sure to enable it -->
<receiver
android:name=".InternetConnectorReceiver"
android:enabled="true">
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
Required permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
InternetConnectorReceiver.class
public class InternetConnectorReceiver extends BroadcastReceiver {
// you can perform the action based on InternetConnected or not based on value of this variable.
public static boolean IsInternetConnected = true;
public InternetConnectorBroadcastReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
try {
boolean isVisible = NameOfapplicationclass.isActivityVisible();
// If it is visible then trigger the task else do nothing
if (isVisible == true) {
if (isInternetConnected(context)) {
IsInternetConnected = true;
}
else
{
IsInternetConnected = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static boolean isInternetConnected(Context context) {
ConnectivityManager cmObj = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cmObj.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
Add Following code in application class
public static boolean activityVisible;
public static boolean isActivityVisible() {
return activityVisible; // return true or false
}
public static void activityResumed() {
activityVisible = true;// this will set true when activity resumed
}
public static void activityPaused() {
activityVisible = false;// this will set false when activity paused
}
You have to use BroadcasrReceive
try this.
Create class for BroadcastReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
//Do your code
}
}
and register it in manifest file like this
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--Custom Broadcast Receiver for checking Internet Connectivity-->
<receiver
android:name=".extras.ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<!--End-->
Connectivity Receiver Class:
public class ConnectivityReceiver extends BroadcastReceiver {
public static ConnectivityReceiverListener connectivityReceiverListener;
public ConnectivityReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent arg1) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
}
}
/**
* Checking if internet connection is active or not
* #return
*/
public static boolean isConnected() {
ConnectivityManager
cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
Activity Code:
public class HomeActivity extends AppCompatActivity
implements ConnectivityReceiver.ConnectivityReceiverListener {
/**
* Callback will be triggered when there is change in
* network connection
*/
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if (!isConnected) {
// show dialog \\
} else {
// check if dialog is visible \\
// if visible then dismiss else do your stuff \\
}
}
#Override
protected void onResume() {
super.onResume();
// Register connection status listener \\
MyApplication.getInstance().setConnectivityListener(this);
}
}
My Application class code and set it in manifest:
public class MyApplication extends Application {
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
//-------Broadcast Receiver for Checking Internet Connection----------\\
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
//----------------------------------------------------------------------\\
}
When phone's network status changed, it will send a broadcast. So you just need a BroadcastReceiver.
For more detail check official documentation
I have BroadCastReceiver that control my connectivity.
I would, when I lost connection, show message, but not generic toast, but a "layout" that I designed.
my broadcast is a generic broadCast for connection:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo()!=null){
Toast.makeText(context, "Connected to Internet", Toast.LENGTH_LONG).show();
}
else{
/** HERE INSTEAD OF TOAST, IWOULD DISPLAY MESSAGE ON ACTIVITY **/
Toast.makeText(context, "not connection", Toast.LENGTH_LONG).show();
Log.i("INTERNET", "---------------------> Internet Disconnected. ");
}
}
}
And my "no_connection_layout"
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="52dp"
android:text="No InterNeT"
android:id="#+id/no_connection"
android:layout_weight="1"
android:layout_gravity="center|top"
android:gravity="center"
android:background="#android:color/holo_green_dark"
android:textStyle="bold"
android:textColor="#ffffff"
/>
</FrameLayout>
Is there a way for show this layout indistinctly current activity?
#Override
public void onReceive(final Context context, final Intent intent) {
//Obviously cleanup where you do this stuff, to make it efficient
//If your context is a fragment you need to cast to fragment and then do getActivity instead
final View noConnectionBanner = ((Activity) context).findViewById(R.id.no_connection)
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null) {
noConnectionBanner.setVisibility(View.GONE);
} else {
noConnectionBanner.setVisibility(View.VISIBLE);
}
}
Just trigger a function and write the view elements that you want to show.
public class ConnectionBroadReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
} else {
Visibler();
}
}
}
#Override
protected void onResume() {
this.connectionBroadReceiver = new ConnectionBroadReceiver();
registerReceiver(this.connectionBroadReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(this.connectionBroadReceiver);
super.onPause();
}
Then inside main program,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
floatingActionButton = (FloatingActionButton) findViewById(R.id.floater);
}
private void Visibler() {
floatingActionButton.setVisibility(View.VISIBLE);
}
Create a Global Boolean and make it true when There is internet Connectivity and false when it is not connected.
And then create a async task class doinBackground method and check it continuosly when the variable changes and from postExecute method you can make changes in the UI. if you need more help pm me .
So I just implemented a checking connectivity method, but should I do this for every activity? Is there a simpler way to continually check for connectivity?
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
First create a ConnectivityChangeReceiver like the following:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
private OnConnectivityChangedListener listener;
public ConnectivityChangeReceiver(OnConnectivityChangedListener listener) {
this.listener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
listener.onConnectivityChanged(isConnected);
}
public interface OnConnectivityChangedListener {
void onConnectivityChanged(boolean isConnected);
}
}
Then create a BaseActivity which extends all of your activites:
public class BaseActivity extends Activity implements OnConnectivityChangedListener {
private ConnectivityChangeReceiver connectivityChangeReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
connectivityChangeReceiver = new ConnectivityChangeReceiver(this);
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(connectivityChangeReceiver, filter);
}
#Override
public void onConnectivityChanged(boolean isConnected) {
// TODO handle connectivity change
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(connectivityChangeReceiver);
}
}
(If you don't want a BaseActivity, you can implement OnConnectivityChangedListener in all of your activities. But in that case you have to register the receiver in all of your Activity.)
You can check this out: This is service that will continuously check the connection. This will be the proper way to do it
`private void installListener() {
if (broadcastReceiver == null) {
broadcastReceiver = 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("InternalBroadcastReceiver", info.toString() + " "
+ state.toString());
if (state == State.CONNECTED) {
onNetworkUp();
} else {
onNetworkDown();
}
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
}`
Look on this link: Android service to check internet connectivity?
Create some sort of util class, for example ConnectionUtils.
Add a public static method to that class and add a Context object to the parameters. For example:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
Then in your Activity just call ConnectionUtils.isNetworkAvailable(this) to know if you're connected.
It would even be better to create some sort of base Activity that you extend with this method in it.
public abstract class BaseActivity extends Activity {
protected boolean isConnected() {
return ConnectionUtils.isNetworkAvailable(this);
}
}
And then let all your Activities extend BaseActivity instead of Activity
You should check before every request to the internet! The user can terminate the connection at any given time... even while your Activity is running.
I suggest you make an Utils class and put this method inside and make it public static so you can access it from everywhere within the Application.
I say it is better to check before every request. It might happen that the connection got broken in between. So its not wise to rely on a check sometime earlier
In my app I have 4 activities. if any network changes i want update the activity which is in foreground state. i wrote one broadcast receiver for network changes. but I want to update activity from that broadcast receiver.
This is my 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()) {
// i need to update activity ?????
}
}
}
In the manifest file :
<application
android:name=".MyApp"
....
</application>
then Create this class to store current activity context:
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private static Activity mCurrentActivity = null;
public static Activity getCurrentActivity(){
return mCurrentActivity;
}
public static void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
Create a new Activity :
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (currActivity != null && currActivity.equals(this))
mMyApp.setCurrentActivity(null);
}
}
then :
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()) {
// i need to update activity ?????
TextView tv = (TextView)myApp.getCurrentActivity().findViewById(R.id.your_view_id);
tv.setText("Network is available");
}
}
}
I want to verify the Android system networks continuously in this way, but i think that in this form is not correct, my service should update if the connection on wifi or other network is available.
public class ObjService extends Service{
private final static int NOTIFICATION=1;
public static boolean process;
private NotificationManager state;
private NotificationCompat.Builder objBuilder;
public void onCreate(){
process=true;
state=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
objBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Title")
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.launchimg))
.setSmallIcon(R.drawable.notification_img);
Thread checker=new Thread(){//1
public void run(){//2
while (process){//3
if (verifyConnection()){//4
updateNotificationService("Service is available");
}else{
updateNotificationService("Service is not available");
}//4
try{
Thread.sleep(6000);
}catch(InterruptedException e){
//..printLog..
}
}//3
};//2
};//1
checker.start();
.
.
.
my function verifyConnection() is:
public boolean verifyConnection() {
boolean flag = true;
ConnectivityManager connec = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] net = connec.getAllNetworkInfo();
if (!net[0].isAvailable() && !net[1].isAvailable())
{
flag = false;
}
return flag;
}
updateNotificationService() is:
public void updateNotificacionService(String arg){
objBuilder.setContentText(arg)
.setWhen(System.currentTimeMillis());
state.notify(NOTIFICATION, objBuilder.build());
}
Try this code below to listen whether the connection exist, if the connection state changes it notifies the change,
public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d("app","Network connectivity change");
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
Log.i("app","Network "+ni.getTypeName()+" connected");
}
}
if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
Log.d("app","There's no network connectivity");
}
}
}
Then for manifest,
<receiver android:name=".NetworkStateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Reference: Internet listener Android example
Android 7.0 (API level 24) placed limitations on broadcasts, as
described in Background Optimization. Android 8.0 (API level 26) makes
these limitations more stringent.
Apps can use Context.registerReceiver() at runtime to register a
receiver for any broadcast, whether implicit or explicit.
Documentation reference.
So, here is a utility class that utilizes a context registered BroadcastReceiver , and LifeCycleObserver for achieving Single-responsibility principle
class ConnectionUtil implements LifecycleObserver {
private ConnectivityManager mConnectivityMgr;
private Context mContext;
private NetworkStateReceiver mNetworkStateReceiver;
interface ConnectionStateListener {
void onAvailable(boolean isAvailable);
}
ConnectionUtil(Context context) {
mContext = context;
mConnectivityMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
((AppCompatActivity) mContext).getLifecycle().addObserver(this);
}
void onInternetStateListener(ConnectionStateListener listener) {
mNetworkStateReceiver = new NetworkStateReceiver(listener);
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
// Registering the Context Registered Receiver
mContext.registerReceiver(mNetworkStateReceiver, intentFilter);
}
#OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
// Removing lifecycler owner observer
((AppCompatActivity) mContext).getLifecycle().removeObserver(this);
// Unregistering the Context Registered Receiver
if (mNetworkStateReceiver != null)
mContext.unregisterReceiver(mNetworkStateReceiver);
}
public class NetworkStateReceiver extends BroadcastReceiver {
ConnectionStateListener mListener;
public NetworkStateReceiver(ConnectionStateListener listener) {
mListener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getExtras() != null) {
NetworkInfo activeNetworkInfo = mConnectivityMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
// Connected to the internet
mListener.onAvailable(true);
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
// Not connected to the internet
mListener.onAvailable(false);
}
}
}
}
}
Manifest permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Usage:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectionUtil mConnectionMonitor = new ConnectionUtil(this);
mConnectionMonitor.onInternetStateListener(new ConnectionUtil.ConnectionStateListener() {
#Override
public void onAvailable(boolean isAvailable) {
if(isAvailable)
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
}
});
}
}
Note: NetworkInfo is deprecated as of API 29, and you can use ConnectivityManager.NetworkCallback with its onAvailable() & onLost() callbacks for the same purpose instead of using a BroadcastReceiver. This answer can guide to target this purpose.