Android-在不进行网络通话的情况下检查活动的Internet连接

时间:2018-07-05 09:52:21

标签: android

是否可以在不打网络电话的情况下检查Internet连接?图书馆链接表示赞赏!

我看到的所有示例都是这样的:

 fun hasInternetConnection(): Single<Boolean> {
 return Single.fromCallable {
  try {
  // Connect to Google DNS to check for connection
  val timeoutMs = 1500
  val socket = Socket()
  val socketAddress = InetSocketAddress("8.8.8.8", 53)

  socket.connect(socketAddress, timeoutMs)
  socket.close()

       true
     } catch (e: IOException) {
       false
  }
}
 .subscribeOn(Schedulers.io())
 .observeOn(AndroidSchedulers.mainThread())
 }

3 个答案:

答案 0 :(得分:1)

Reactive Network是适合您的库,因为您已经在使用RxJava。该代码将如下所示:

ReactiveNetwork.observeNetworkConnectivity(context)
            .subscribeOn(Schedulers.io())
            // anything else what you can do with RxJava
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Connectivity>() {
                @Override public void accept(final Connectivity connectivity) {
                    // do something with connectivity
                    // you can call connectivity.getState();
                    // connectivity.getType(); or connectivity.toString();
                }
            });

答案 1 :(得分:0)

尝试以下代码:在onCreate中调用方法

private boolean chechInternetConnection() {

    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            connected = true;
            Log.i("Internet", "Connected");
        } else {
            connected = false;
            Log.i("Internet", "Not Connected");
        }
    }
    return connected;
}

答案 2 :(得分:0)

这将为您提供帮助。我已经在我的项目中使用了它。

fun getConnectivityStatus(context: Context): Boolean {
    try {
        val cm = context
                .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork = cm.activeNetworkInfo
        if (activeNetwork != null) {
            if (activeNetwork.type == ConnectivityManager.TYPE_WIFI)
                return true

            if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE)
                return true
        }
    } catch (aThrowable: Throwable) {
        return false
    }

    return false
}