我在Google Developer上阅读过:



我有以下代码:

公共(public)类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;
    }
}


//

公共(public)类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;
}

}

当我第一次启动应用程序时,此 Intent 总是会触发并显示一个带有网络当前状态的对话框。但是基于此文档,它仅在连接更改时发生吗?如果仅在网络变化时才需要此显示,该怎么办?非常感谢

最佳答案

广播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)
}

关于android - BroadcastReceiver CONNECTIVITY_CHANGE始终在首次启动应用程序中运行吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36449530/

10-08 23:26