onReceive的BroadcastReceiver在android中显示警报2次

时间:2017-09-12 06:51:02

标签: android broadcastreceiver

我正在使用BroadcastReceiver在我的应用程序中实现丢失的互联网连接。代码工作正常但是在互联网连接上显示的警报或断开显示两次。我想一次只显示一次警报或吐司。我是我的Broadcastreceiver的代码

public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
                ConnectivityManager cm =
                        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                //NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

                if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
                        || cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {

                    // notify user you are online
                    Toast.makeText(context.getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();

                } else if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED
                        || cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) {
                    Constants.alert("Please check your internet connection", context);

                    // notify user you are not online
                }

1 个答案:

答案 0 :(得分:0)

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

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

要知道消息已被调用,你可以有一个静态布尔值,它在connect和disconnect之间切换,只在你收到一个连接并且boolean为true时调用你的子例程。类似的东西:

public class ConnectionChangeReceiver extends BroadcastReceiver {

private static boolean 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;
    }
}
}