我调用以下函数onCreate
,当我在进行此活动时打开和关闭设备上的网络连接时,它会完美地显示该消息。但是,当我在设备上的网络关闭时打开此活动时,它不会显示网络已关闭的消息,而当我在网络打开时打开此活动时,它会显示我正在运行的消息连接到网络。
private fun checkConnection() {
connectivity = CheckConnectivity(application)
connectivity.observe(this, { isConnected ->
if (isConnected) {
Toast.makeText(this,"You are connected to the internet",Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this,"You are NOT connected to the internet",Toast.LENGTH_SHORT).show()
}
})
}
Run Code Online (Sandbox Code Playgroud)
以下是CheckConnectivity.kt
class CheckConnectivity(private val connectivityManager: ConnectivityManager) :
LiveData<Boolean>() {
constructor(application: Application) : this(
application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
)
private val networkCallback = @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
object: ConnectivityManager.NetworkCallback(){
override fun onAvailable(network: Network) {
super.onAvailable(network)
postValue(true)
}
override fun onLost(network: Network) {
super.onLost(network)
postValue(false)
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onActive() {
super.onActive()
val builder=NetworkRequest.Builder()
connectivityManager.registerNetworkCallback(builder.build(),networkCallback)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onInactive() {
super.onInactive()
connectivityManager.unregisterNetworkCallback(networkCallback)
}
}
Run Code Online (Sandbox Code Playgroud)
这可以通过调用来完成onUnavailable()
,但遗憾的是,该函数没有响应。检查如果未找到 Wi-Fi AP,则不会调用 NetworkCallback 的 onUnavailable() 方法
但你可以通过添加isconnected()
到你的MainActivity.kt
. 我知道这不是您正在寻找的答案,但通过这样做您的问题将会得到解决,欢呼。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
checkConnection()
}
override fun onStart() {
super.onStart()
Toast.makeText(this, if (isConnected()) "You are connected to the internet" else "You are NOT connected to the internet", Toast.LENGTH_SHORT
).show()
}
private fun checkConnection() {
val connectivity = CheckConnectivity(application)
connectivity.observe(this, { isConnected ->
Log.d("testTag", "checkConnection: Observer Called")
if (isConnected) {
Toast.makeText(this, "You are connected to the internet", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "You are NOT connected to the internet", Toast.LENGTH_SHORT)
.show()
}
})
}
private fun isConnected(): Boolean {
var connected = false
try {
val cm =
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val nInfo = cm.activeNetworkInfo
connected = nInfo != null && nInfo.isAvailable && nInfo.isConnected
return connected
} catch (e: Exception) {
Log.e("Connectivity Exception", e.message!!)
}
return connected
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2458 次 |
最近记录: |