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

时间:2016-04-06 11:15:55

标签: android android-activity broadcastreceiver

我是在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;
}

}

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

1 个答案:

答案 0 :(得分:28)

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

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

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