【问题标题】:onReceive called twice in BroadcastReceiver for Network Listener in androidonReceive 在 BroadcastReceiver 中为 android 中的网络侦听器调用了两次
【发布时间】:2015-01-02 11:09:13
【问题描述】:

当网络状态发生变化时,为什么在接收时调用了两次。

清单:

    <receiver android:name="tv.meterreading.network.NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" >
            </action>
        </intent-filter>
    </receiver>

【问题讨论】:

标签: android broadcastreceiver android-wifi


【解决方案1】:

接收多个广播是设备特定的问题。有些手机只发送一个广播,而其他手机发送 2 或 3 个。但有一种解决方法:

假设您在 wifi 断开连接时收到断开消息,我猜第一个是正确的,而另外两个只是出于某种原因的回声。

要知道消息已被调用,您可以有一个静态布尔值,在连接和断开之间切换,并且仅在您收到连接并且布尔值为真时才调用您的子例程。比如:

公共类 ConnectionChangeReceiver 扩展 BroadcastReceiver { 私有静态布尔 firstConnect = true;

@Override
public void onReceive(Context context, Intent intent) {
    final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    if (activeNetInfo != null) {
        if(firstConnect) { 
            // do subroutines here
            firstConnect = false;
        }
    }
    else {
        firstConnect= true;
    }
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    相关资源
    最近更新 更多