BroadcastReceiver CONNECTIVITY_CHANGE总是在第一次启动应用程序中运行?

我在Google Developer上阅读了它:

(“android.net.conn.CONNECTIVITY_CHANGE”)操作只要连接详细信息发生更改

我有这个代码:

公共类MainActivity扩展AppCompatActivity {

private NetworkChangeReceiver receiver; private boolean connIntentFilterIsRegistered; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); receiver = new NetworkChangeReceiver(); } @Override protected void onPause() { super.onPause(); if (connIntentFilterIsRegistered) { unregisterReceiver(receiver); connIntentFilterIsRegistered = false; } } @Override protected void onResume() { super.onResume(); if (!connIntentFilterIsRegistered) { registerReceiver(receiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); connIntentFilterIsRegistered = true; } } 

和//

公共类NetworkUtil {

 public static int TYPE_WIFI = 1; public static int TYPE_MOBILE = 0; public static int TYPE_NOT_CONNECTED = 2; public static int getConnectivityStatus(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { return TYPE_WIFI; } if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { return TYPE_MOBILE; } } return TYPE_NOT_CONNECTED; } public static String getConnectivityStatusString(Context context) { int conn = NetworkUtil.getConnectivityStatus(context); String status = null; if (conn == TYPE_MOBILE) { status = "Mobile cellular enabled"; } else if (conn == TYPE_WIFI) { status = "Wifi enabled"; } else if (conn == TYPE_NOT_CONNECTED) { status = "Not connected to internet"; } return status; } 

}

当我第一次启动应用程序时,此意图始终会触发并显示一个包含当前网络状态的对话框。 但基于这个文档,它只发生在连接改变时? 如果我只想在网络改变的时候想要这个显示器,我该怎么办? 非常感谢

广播android.net.conn.CONNECTIVITY_CHANGE是一个粘性广播 。 这意味着无论何时为此ACTION注册BroadcastReceiver ,它都将立即被触发,并且将使用最新的广播连接更改来调用onReceive() 。 这使您可以获得连接的当前状态,而无需等待更改。

如果要忽略当前状态,并且只想处理状态更改,可以将其添加到onReceive()

 if (isInitialStickyBroadcast()) { // Ignore this call to onReceive, as this is the sticky broadcast } else { // Connectivity state has changed ... (your code here) }