Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android network state change detection takes time

I am trying to detect network state change in my android app. I followed the answer in that question : Check INTENT internet connection

This works, but it takes time for broadcastreceiver to detect changes. When i turn wifi on or off, about 10 seconds later the onReceive() method is called. Why is that taking so much time? Can anyone help?

Thanks

Here is my code:

public class NetworkStateReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent 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");
            Toast.makeText(context, "CONNECTED", Toast.LENGTH_LONG).show();
        } else if (intent.getBooleanExtra(
                ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
            Toast.makeText(context, "DISCONNECTED", Toast.LENGTH_LONG).show();
            Log.d("app", "There's no network connectivity");
        }
    }

}

}

and in my Manifest's application tag:

<receiver android:name="com.mypackage.NetworkStateReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
</receiver>
like image 307
yrazlik Avatar asked Aug 14 '14 10:08

yrazlik


People also ask

What is Android network State?

The mobile network state is an indicator on smartphones and similar mobile devices that shows whether the device is connected to a telecom carrier's mobile network.

How do I find network changes?

Using 'ConnectivityManager' classCallback 'networkCallback' will receive connection-established or connection-dropped events. We can see that 'ConnectivityManager' class has different methods for registering network callback on different Android API so they can work nicely, on different Android versions.


1 Answers

I found the solution.

Instead of extending BroadcastReceiver class and creating NetworkStateChangeReceiver, i created a broadcastreceiver on my activity and registered it there. Now it works and onReceive() method is triggered immediately.

like image 60
yrazlik Avatar answered Oct 21 '22 06:10

yrazlik