1

几天前,我在 Stackoverflow 帖子中发现了一个代码,用于了解我的设备连接何时使用广播接收器发生变化。我将它调整到我的应用程序并且它可以工作,但是每次我打开/关闭我的互联网连接时,我的接收器上的 onReceive 方法都会被调用两次。这是为什么?无论如何,我的应用程序运行良好,但是当一次就足够时,我会执行两次操作。

这是我的接收器:

public class ConnectivityReceiver extends BroadcastReceiver {

    private Context mContext;

    Thread network_check = new Thread(new Runnable(){
        public void run() {
            if (NetworkHelper.isOnline(mContext)) {
                     // Do some stuff
            }
        }
    });

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("MonitorInternetConnectivity", "onReceive");
        mContext = context;
        network_check.start();
    }
}

网络助手类:

public class NetworkHelper {

    public static boolean isOnline(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting() && canHit()) {
            return true;
        }
        return false;
    }

    public static boolean canHit() {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(3000);
            urlConnection.connect();
            urlConnection.disconnect();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } 
    }
}

我将此添加到我的清单中(以及所需的权限):

<receiver android:name=".receivers.ConnectivityReceiver" android:exported="false">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
</receiver>

每次我的连接更改时,日志都会显示两次“onReceive”。为什么?

谢谢!

- - - - - - - - 编辑 - - - - - - - - - - -

我添加有关收到的意图的信息。每次连接发生变化时,收到的两个意图都是完全相同的。

设备离线时:

Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x10000010 cmp=com.pfc.app/.receivers.ConnectivityReceiver (has extras) }
Extras:
    NetworkInfo: type: WIFI[], state: DISCONNECTED/DISCONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: false
    noConnectivity: true
    inetCondition: 0

设备上线时:

Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x10000010 cmp=pfc.dani.palou/.receivers.ConnectivityReceiver (has extras) }
Extras:
    NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true
    inetCondition: 0
4

0 回答 0