我正在开发一个 android 应用程序,但我遇到了下一个问题:我实现了用于连接更改的广播接收器,并且onReceive当同时启用 3G 和 Wifi 时,该方法似乎连续调用了 4 次。
所以我的问题是:
有没有办法只监听互联网连接,而不是网络变化?
或者有什么办法onReceive可以在3G和Wifi同时启用的情况下只调用一次方法?
这是我的代码:
public class NetworkChangeReceiver extends BroadcastReceiver {
public static final String TAG = "NetworkMonitoring";
@Override
public void onReceive(Context context, Intent intent) {
if (isOnline(context)) {
Log.v(TAG, "Connected!");
// update(context);
} else {
Log.v(TAG, "Not connected!");
// stopUpdate(context);
}
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
return true;
return false; …Run Code Online (Sandbox Code Playgroud)