user7396065
user7396065

Reputation: 39

how define Broadcastreceiver with CONNECTIVITY_CHANGE?

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

Upvotes: 1

Views: 736

Answers (4)

Sami Kanafani
Sami Kanafani

Reputation: 15741

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

Upvotes: 2

user7396065
user7396065

Reputation: 39

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

Upvotes: 0

aarnaut
aarnaut

Reputation: 557

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());

Upvotes: 0

Mohammad Arman
Mohammad Arman

Reputation: 7065

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>

Upvotes: 0

Related Questions