unfortunately app is getting stopped while checking for network

The above code was not properly working for wi-fi connection. This is the Modified

SIMPLE ONE

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

inside application tag of androidmanifest.xml

<receiver android:name="android.YOUR-JAVA-CLASS-PATH.BackgroundSync" android:enabled="true">
      <intent-filter>
          <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
      </intent-filter>
</receiver>

BackgroundSync.java

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

public class BackgroundSync extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, 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 Log.i("INTERNET","---------------------> Internet Disconnected. ");
    }
}

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.

https://developer.android.google.cn/reference/android/net/ConnectivityManager.html?hl=zh-cn#CONNECTIVITY_ACTION


NOTE: If you're targeting android N Preview. Above receiver will not work as per constrained restricted by Google.

Link: https://developer.android.com/preview/features/background-optimization.html#connectivity-action

Use: WorkManager or JobScheduler for same.


Have you added this in AndroidManifest.xml?

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

if you have added above then check this code:

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

and

public class UpdateReceiver extends BroadcastReceiver {

    @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();   
          if (isConnected)       
              Log.i("NET", "Connected" + isConnected);   
          else 
              Log.i("NET", "Not Connected" + isConnected);
    }
}