Android: 在boolean方法中使用BroadcastReceiver

Android: Use BroadcastReceiver in the boolean method

为了了解设备此时是否有互联网连接,我将 check_internet_connection() 的代码放入 BroadcastReceiver 中。问题我需要这种方法来重新调整布尔值,但我该如何管理它?

当前错误是这些行"return true"或"return false":"Void methods cannot return a value"

 public boolean check_internet_connection() {
  registerReceiver(new BroadcastReceiver() {

   @Override
   public void onReceive(Context context, Intent intent) {
    ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
      .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
     return true;
    }

    NetworkInfo mobileNetwork = cm
      .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
     return true;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
     return true;
    }
    return false;
   }

  }, new IntentFilter(ConnectivityManager.EXTRA_NETWORK_TYPE));
 }

public static boolean hasInternetConnection(Context context) {
        ConnectivityManager check = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

//getActiveNetworkInfo() Returns details about the currently active default data network.
    NetworkInfo info = check.getActiveNetworkInfo();

    return info != null && info.isConnected();
}

希望对您有所帮助