1

I am android beginner and want to declare a broadcastreceiver which reacts on CONNECTIVITY_CHANGE. I have tried the following:

private void checkInternet () {
    IntentFilter ifilter = new IntentFilter ("android.net.conn.CONNECTIVITY_CHANGE");
    broadcastreceiver = new BroadcastReceiver () {
        @Override
        public void onReceive (Context Context, Intent Intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService (getApplicationContext (). CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo ();
            if (networkInfo! = null && networkInfo.getState () == NetworkInfo.State.CONNECTED)
                Toast.makeText (getApplicationContext (), "Internet", Toast.LENGTH_SHORT) .show ();
            else
                Toast.makeText (getApplicationContext (), "No Internet", Toast.LENGTH_SHORT) .show ();
        }
    };
    this.registerReceiver (broadcastreceiver, ifilter);
}

In Actitvity.onCreate I call checkInternet. When I disconnect the Internet both messages "No Internet" and "Internet" are displayed. And when I connect the Internet both messages "No Internet" and "Internet" come again and in the same order. Can someone please tell me why the Broadcastreceiver 2 times starts and shows 2 different status pro Start? I thank you in advance

user7396065
  • 39
  • 1
  • 7
  • Possible duplicate of [Broadcast receiver for checking internet connection in android app](https://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app) – mrid Oct 16 '17 at 09:18
  • thank you very much for the quick response. I have already read that post and other posts too. In that the broadcastreceiver is called twice, but with each call comes the same message (eg "Internet" "Internet" or "No Internet" "No Internet"). In my APP each call shows 2 different status ("No Internet" AND "Internet"). I declare the receiver only at the point, not in the manifest. Can you help please? – user7396065 Oct 16 '17 at 09:39
  • have you included the `CONNECTIVITY_CHANGE` permission in manifest ? – mrid Oct 16 '17 at 09:41
  • no i did not do that, because I have registered the receiver in the Activity. I have wrote below that my Android runs on a VM(VMware Player). Maybe the Broadcastreiever does not work properly on VMs? – user7396065 Oct 16 '17 at 10:23

4 Answers4

2

if you just need to check for internet connectivity, you can use the following. In your activity

 @Override
 protected void onCreate(Bundle savedInstanceState){
       ConnectionStateMonitor connectionStateMonitor = new ConnectionStateMonitor();
    connectionStateMonitor.enable(this);
 }

and add this class inside your activity

public class ConnectionStateMonitor extends ConnectivityManager.NetworkCallback {

    final NetworkRequest networkRequest;

    public ConnectionStateMonitor() {
        networkRequest = new NetworkRequest.Builder().
                addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();
    }

    public void enable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.registerNetworkCallback(networkRequest , this);
    }
    // Likewise, you can have a disable method that simply calls ConnectivityManager#unregisterCallback(networkRequest) too.

    @Override
    public void onAvailable(Network network) {
         //do what you want when Connection is available
    }
    @Override
    public void onLost(Network network){
        //Connection Lost
    }
}

I think this will be easier than using a broadCast receiver

Sami Kanafani
  • 14,244
  • 6
  • 45
  • 41
  • hey sami, thank you for your help. I have tried your solution too. The result is exact the same. No Internet => onLost and onAvailable called, with internet => onLost and onAvailable called. My Android runs on a VM (VMware Player), can it be that CONNECTIVITY_CHANGE does not work properly on VMs? – user7396065 Oct 16 '17 at 10:20
  • hey sami, see please my comment above – user7396065 Oct 16 '17 at 11:04
  • can you please check if it is working on an android emulator, if it is not working also, please your whole code – Sami Kanafani Oct 16 '17 at 11:14
  • it works on the emulator too. I think i know why on the VM always 2 messages are displayed("No Internet" and then "Internet"). When i disconnect the internet on my pc, i see in the VM the connection symbol and exclamation mark next to it. This says(i think) that the VM has connection but the connection is disturbed. But when i disconnect the internet direkt in the VM i see the connection symbol not at all and all above solutions work on the VM too. I think i shoud not work with ConnectivityManager.CONNECTIVITY_ACTION rather with ACTION_RESTRICT_BACKGROUND_CHANGED. Not sure but i will try it – user7396065 Oct 16 '17 at 13:59
0

Try the following example:

Implementation:

public class NetworkReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
                Log.d("Network status: ", "Connected");
            } else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) {
                Log.d("Network status: ", "Not connected");
            }
        }
    }
}

Add receiver in your AndroidMenifest:

<receiver
    android:name=".receivers.NetworkReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
Mohammad Arman
  • 7,020
  • 2
  • 36
  • 50
  • thank you very much Mohammad, I have tried your solution, but my app behaves the same, 2 messages ("No Internet" and "Internet") when I disconnect the Internet and 2 messages ("No Internet" and "Internet", exactly in the same order) when I connect the internet again. This drives me crazy. how can it be that the app has both internet and no internet at the same time? Any idea please? – user7396065 Oct 16 '17 at 10:01
  • Please try this solution in a real device. – Mohammad Arman Oct 16 '17 at 10:41
  • i have tried your solution and the solution from sami on a real device. Both solutions works on the device. The only difference between the 2 solutions: your solution shows 2 times "not connected" wenn i disconnect and 1 time "connected" when i connect. Sami's solution shows 1 time "not connected" when i disconnect and 2 times "connected" when i connect. but that's not bad. The question is why do not work all the solutions on the VM? this is strange. I disconnect and connect my computer so that the VM looses or gets the internet(Ethernet). What is wrong here? – user7396065 Oct 16 '17 at 11:04
0

Create a new class which will extend from BroadcastReceiver. Here you define the intent filter for connectivity change. Also we create a new private method to retrieve the current status of the network connection.

public class ConnectivityChangedBroadcastReceiver extends BroadcastReceiver {

public static IntentFilter getIntentFilter() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    return intentFilter;
}

@Override
public void onReceive(Context context, Intent intent) {
    if (isNetworkAvailable(context)) {
        // Network is available
    } else {
        // Network is not available
    }
}

private boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}}

Now register your broadcast receiver in the activity or application class like this. Please note that Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver in their manifest. Apps will still receive CONNECTIVITY_ACTION broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid. So, if you want to target latest versions of Android then make sure you register the receiver in the code and not manifest

ConnectivityChangedBroadcastReceiver connectivityChangedBroadcastReceiver;
connectivityChangedBroadcastReceiver = new ConnectivityChangedBroadcastReceiver();
registerReceiver(connectivityChangedBroadcastReceiver, ConnectivityChangedBroadcastReceiver.getIntentFilter());
aarnaut
  • 507
  • 6
  • 17
  • Hi Ahmed, the problem is apparently with the VM on which Android is running, on a real device work all solutions. see please my comment at Mohammad Arman. Thank you – user7396065 Oct 16 '17 at 11:06
0

as said all solutions work and the problem is the VM. When I disconnect the Internet on my computer, the VM still has the physical connection but only the communication is not possible. Therefore the messages "Not connected" "connected" are shown in this order when disconnecting or connecting on my PC

user7396065
  • 39
  • 1
  • 7