【问题标题】:BroadcastReceiver CONNECTIVITY_CHANGE always run in the first time launch app?BroadcastReceiver CONNECTIVITY_CHANGE 总是在第一次启动应用程序中运行?
【发布时间】:2016-04-06 11:15:54
【问题描述】:

我在 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 android-activity broadcastreceiver


    【解决方案1】:

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

    【讨论】:

    • 非常感谢。我在看到你的答案之前就这样做了,它有效:D
    猜你喜欢
    • 2020-07-05
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    相关资源
    最近更新 更多