前几天我在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