2

In my application I want to notify if a device has been lost network connection and if it's connected to a network again.

So I wrote a Broadcastreceiver like this:

class NetworkReceiver() : BroadcastReceiver() {

override fun onReceive(context: Context?, intent: Intent?) {

    if (isNetworkConnected(context)) {
        //do some stuff
    } else {
        //do smoke stuff
    }
}

private fun isNetworkConnected(context: Context?): Boolean {
    val connectivityManager: ConnectivityManager? = context?.getSystemService(Context.CONNECTIVITY_SERVICE)
            as ConnectivityManager?
    if (connectivityManager != null) {
        if (Build.VERSION.SDK_INT < 23) {
            val networkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo
            if (networkInfo != null) {
                return networkInfo.isConnected
                        && networkInfo.type == ConnectivityManager.TYPE_WIFI
                        || networkInfo.type == ConnectivityManager.TYPE_MOBILE
            }
        } else {
            val network: Network? = connectivityManager.activeNetwork
            if (network != null) {
                val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
                return (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
                        || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
                        || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN))
            }
        }
    }
    return false
}

My question how can I register this broadcast receiver in my activity to trigger the NetworkReceiver when my device is connected or disconnected from the network. Which IntentFilter should I use?

dudi
  • 5,523
  • 4
  • 28
  • 57
  • Possibly duplicated with https://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app – Bach Vu Jan 31 '19 at 07:39
  • No because I want to register my broadcast receiver programmatically. The packages that where using in the answer are deprecated or don't exist anymore – dudi Jan 31 '19 at 07:40
  • Hey @dudi Did you find the proper solution for this?? – Parag Pawar Mar 20 '20 at 06:03

2 Answers2

1

BroadcastReceiver

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;
        }
    }
}

In Manifest File :

<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>
Karan Khurana
  • 575
  • 8
  • 20
  • 5
    ConnectivityManager.CONNECTIVITY_ACTION is deprecated – dudi Jan 31 '19 at 07:46
  • 1
    This example works only for API Level 21+. Should I use the Broadcast Receiver for under API Level 21 and this https://stackoverflow.com/a/36447866/4776577 solution for Api Level 21+ ? – dudi Jan 31 '19 at 08:27
  • This should solve your issue : https://stackoverflow.com/a/26114247/4776577 – Karan Khurana Jan 31 '19 at 08:44
  • Sorry, I don't really get it why this solved my issue? Can you explain me the details? – dudi Jan 31 '19 at 08:51
  • With this your application responds to changes made in network through Receiver and receives change in network through Service Manager. Mark answer as accepted if it helped in anyway. – Karan Khurana Jan 31 '19 at 09:54
1

In order to register your BroadcastReceiver programmatically, you can use the following code:

private NetworkReceiver reciver;


@Override
    protected void onStart() {
        super.onStart();

        reciver = new NetworkReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        this.registerReceiver(reciver, filter);
    }


      @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(reciver);

    }