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>
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With