使用asynctask检查Internet连接

时间:2018-02-01 06:31:53

标签: android android-asynctask xamarin.android

我检查互联网连接是否有网络访问权限,但我总是在" listener.onComplete(b);" :

<h2>Toggle Switch</h2>

<label class="switch">
  <input type="checkbox">
  <span class="slider"></span>
</label>

<label class="switch">
  <input type="checkbox" checked>
  <span class="slider"></span>
</label><br><br>

<label class="switch">
  <input type="checkbox">
  <span class="slider round"></span>
</label>

<label class="switch">
  <input type="checkbox" checked>
  <span class="slider round"></span>
</label>

这是我的代码: enter image description here enter image description here

这就是我执行的方式:

enter image description here

enter image description here

谢谢!

2 个答案:

答案 0 :(得分:0)

我建议使用public static boolean isNetworkAvailable(Context context) { if (context == null) return false; try { ConnectivityManager connManager = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE); NetworkInfo info = connManager.getActiveNetworkInfo(); if (info != null && info.isAvailable() && info.isConnected() && isConnectionAvailable(info)) { return true; } } catch (Exception ex) { ex.printStackTrace(); return false; } return false; } private static boolean isConnectionAvailable(NetworkInfo info) { return info.getType() == ConnectivityManager.TYPE_WIFI || (info.getType() == ConnectivityManager.TYPE_MOBILE && info.getSubtype() != TelephonyManager.NETWORK_TYPE_UNKNOWN); } 来检查网络可用性。使用以下代码段检查连接。

您可以在进行任何网络操作之前​​调用此功能。

<?php namespace Modules\Mailbox;

use Modules\Mailbox\Interfaces\IMailbox;
...
use Modules\Mailbox\Repositories\MailboxRepository;
use Illuminate\Support\ServiceProvider;

/* Use these instead of DB facade */
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Connectors\ConnectionFactory;

class MailboxServiceProvider extends ServiceProvider 
{
  protected $defer = true;

  public function register()
  {
    $this->app->bind(IMailbox::class, function($app) {
      return new MailboxRepository(
        ..., new DatabaseManager($app, new ConnectionFactory($app))
      );
    });
  }

  public function provides()
  {
    return [IMailbox::class];
  }
} 

答案 1 :(得分:0)

您也可以尝试这个..

要检查网络连接是否可用,请使用getActiveNetworkInfo()方法和isConnected()。

{{1}}