我正在尝试通过广播接收器检测互联网连接和断开连接。
我的广播接收器:
public class InternetConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(isOnline(context))
{
Log.e("internet", "connected");
}
else
{
Log.e("internet", "disconnected");
}
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
}
}
在清单中:
<receiver
android:name=".receivers.InternetConnectivityReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
我不明白当我连接或断开互联网时为什么onReceive方法会运行两次?
任何人都可以帮助我吗?
更新
这是我的logcat输出:
01-01 17:26:06.640 17883-17883/ir.ac.um.androidhistory E/internet: connected
01-01 17:26:26.270 17883-17883/ir.ac.um.androidhistory E/internet: connected
01-01 17:27:18.990 17883-17883/ir.ac.um.androidhistory E/internet: disconnected
01-01 17:27:37.910 17883-17883/ir.ac.um.androidhistory E/internet: disconnected
01-01 17:27:59.800 17883-17883/ir.ac.um.androidhistory E/internet: connected
01-01 17:28:08.120 17883-17883/ir.ac.um.androidhistory E/internet: connected