且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android的网络状态变化检测需要时间

更新时间:2022-10-18 12:08:55

我找到了解决办法。

不是扩展广播接收器类和创建NetworkStateChangeReceiver的,我创建了我的活动一个BroadcastReceiver和注册它。现在,它的工作原理和的onReceive()方法被立即触发。

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>

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.