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>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…