如何使用RxJava/Rx安卓Kotlin实现互联网安卓的检查



查看互联网的答案发布在2014年的这篇文章中:https://stackoverflow.com/a/27312494/12359431

然而,在其中一个答案中,有一段代码

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())
}

我已经尝试过将上面的代码实现为底部的代码。然而,它只是崩溃了,我找不到任何关于应用程序崩溃原因的错误。

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/* Initialise Azure Service Adapter */
AzureServiceAdapter.Initialize(this)
hasInternetConnection().subscribe{hasInternet->
/*Call database and check phone number*/
Log.i("Logger", "Connected")}
/* Authentication */
authUser()
}
}

这是我的实现

implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
implementation 'io.reactivex.rxjava3:rxjava:3.0.0'

我是否缺少什么或不应该添加到我的MainActivity文件中?或者我的kotlin应用程序为什么崩溃的线索?

这是因为您不能在主线程上调用它。

检查是否在清单中添加了Internet权限。

hasInternetConnection()
.subscribeOn(Schedulars.io())
.observeOn(AndroidSchedulars.mainThread()).subscribe{hasInternet->
/*Call database and check phone number*/
Log.i("Logger", "Connected")}

最新更新