Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

broadcastreceiver - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...